Question

I have opened a binary file as below

FILE *p;
p=fopen("filename.format","rb");

How can I find the end of the file?

Was it helpful?

Solution

The fread function fread returns the number of bytes actually read. So if the number of bytes read is lower that the number of bytes to be read, you are likely at the end of file.

Furthermore the feof function will also tell you if you are at the end of the file.

To find out the size of the file without actually reading it:

  long Size;
  FILE *p;
  p = fopen("filename.format","rb");
  fseek (p, 0 , SEEK_END);
  Size = ftell (p) ;
  rewind (p);

OTHER TIPS

In C++ I usually jump to the end of the file using ifstream::seekg and giving it the ios::end argument for position. The ANSI-C equivalent of seekg is

int fseek ( FILE * stream, long int offset, int origin );

Where origin can be SEEK_SET, SEEK_CUR, SEEK_END.
Trying this would jump to the end of the file:

fseek(p, 0, SEEK_END);

Then, once at the end of the file, just use

long int ftell ( FILE * stream );

to tell your program where the file ends.
For an example, the following code would set the size variable to the physical size - in bytes - of the file, and then jump back to the beginning of the file:

FILE *p = fopen("filename.format", "rb"); // open binary file

fseek(p, 0, SEEK_END); // jump to end of file

long int size = ftell(p); // get size of file

fseek(p, 0, SEEK_SET); // jump back to beginning of file

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top