1

I have a class that reads "blocks" from a binary file. I use it this way :

while(log.HasNextBlock()) {
    block = log.GetNextBlock();
}

My problem is that i need to check inside of the function HasNextBlock() if i am at the end of the file, in which case i would return false. I'm tring to use feof() to check that, but i read i had to do a read operation before calling feof(), but in my case, the read operation is done in GetNextBlock(), i.e after the call to feof().

Is there a way to see if i am at the end of the binary file without doing an operation that would modify the "context" (i.e not change the current position in the file or whatever other variable) ?

Thanks for your help ! :)

Virus721
  • 8,061
  • 12
  • 67
  • 123

5 Answers5

6

Before you start your loop, call fseek to go to the end of file (i.e. with SEEK_END), and use ftell to find the current position. This will let you know where the EOF will be. Then use fseek again go back to the beginning of file with SEEK_SET, and proceed with the loop. When you need to know if you are at EOF, call ftell and compare the position with the size of the file that you stored before entering the loop.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

When opening the file you can seek to the end of the file, get the file position, and then seek back to the beginning of the file again.

Then when you need to know if there is more to read in the file, you simple check the current file position and compare it to the one at the end.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

Thanks for your answers everyone ! I just found the solution :

long lOldPos = ftell(m_pFile); // Saving current position
fseek(m_pFile, 0, SEEK_END); // Going to end of file
bool bAtEof = lOldPos == ftell(m_pFile); // If end of file position equals old position, we were at eof.
if( ! bAtEof) {
    // Position was changed, restoring it.
    fseek(m_pFile, lOldPos, SEEK_SET);
}
Virus721
  • 8,061
  • 12
  • 67
  • 123
1

one way is

while ((c = getchar()) != EOF)

You can find all ways here

Additional Info Difference between Binary and Text file in C

Example

These ways I have collected from internet. You need to try them before use.

Community
  • 1
  • 1
Amol Patil
  • 238
  • 1
  • 2
  • 7
1

After get next block, read one character and check to see if its EOF. If it is, break. If not, then fseek back one byte like this: http://linux.die.net/man/3/fseek

Set your stream to the file you're reading, set offset to -1 (if reading chars which you are), and set whence to SEEK_CUR.

This will let you see the EOF if its there, and if its not, then you'll just continue as normal.

KrisSodroski
  • 2,796
  • 3
  • 24
  • 39