-2

I'm trying to read a file and to work on the last byte a little differently. Here is my code:

 FILE  * file = fopen(path,"rb");
 unsigned char curr;
 while (fread(&in, 1, 1, file) >= 1)
 {
   If (Is_Last_Byte){
      //Does something
   }
   else{
   //Does something else
   }
 }

How do I perform this check? Is it possible to set a pointer to the last byte and during each loop iteration perform this check?

Thanks in advance.

TheKilz
  • 321
  • 1
  • 3
  • 10

1 Answers1

0

Since there is nothing which distinguishes the last byte from any other byte, your best bet is to always read one byte (or buffer) ahead of the byte (buffer) you are processing. When the read ahead returns EOF, you know that the byte (buffer) you are about to process is the last one.

This is essentially the same logical structure as the often-repeated advice that read loops should terminate when the read returns EOF, rather than having the form while(!feof(file)). (The fact that the advice needs to be repeated demonstrates that the message is somehow not getting through :-) ) while(!feof(file)) is wrong precisely because the last byte is not special; even after reading it, it is not known that no more bytes follow.

rici
  • 234,347
  • 28
  • 237
  • 341