1

For pset4's recover.c code, I noticed the following: when I set my while loop to be

while (!feof(inptr)),

all the images get recovered, including the last, but check50 throws an error (TODO) when evaluation the last image (015.jpg).

However, when I rewrote my code, per the walk-through video, to use

while (fread(&buffer, sizeof(buffer), 1, inptr) == 1),

again, all the images get recovered, and the check50 passes. I'm curious why that happens. If I think about the last read of data from the 16th JPG, presumably fread loads that data into the buffer, and then the file's position pointer gets moved to the EOF spot, in which case feof(inptr) will return TRUE. Likewise, if fread is put in the while loop and I've already finished reading in all the data, the file position pointer will be at EOF, and the fread command will not be able to find 512 more bytes, and so it will return something not equal to 1, and again, I'll break out of the loop.

I'm probably missing something subtle, but any answers would be welcome!

6

What is wrong with feof?

per feof's man page, it returns non-zero if the EOF was already reached not whether the next thing to reach as you read is the EOF. this means that it returns non-zero even if there is no further data to read (in which case, if you read, you will reach the EOF).

as feof returns non-zero, the loop executes one more time and subsequently calls to fread and fwrite are made.

reading data past reaching the EOF has an undefined behavior (you don't know what's gonna be stored in the buffer that you're reading into -- we may call that garbage data). yet this garbage data is still appended to the last JPG.

Why fread works?

per fread's man page, it returns a positive value on success and 0 on failure or in case the EOF is reached. when the next thing to reach is the EOF and fread, the EOF is reached and fread returns 0. garbage data may be still written into the buffer, but you never enter the loop as the continuation condition is false, thus, they're never appended to the last JPG.

| improve this answer | |
  • Thanks, Kareem This make sense. Appreciate it! – Richard Jun 11 '15 at 2:48
  • Thanks for the clarification. – Chuma Umenze Sep 30 '17 at 22:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .