Home fstat always returns 0 length to get file size

I am trying to use my own function to get file size from file. I will use this to allocate memory for a data structure to store file information.

The file size function is as follows:

long fileSize(FILE *fp){ long start; fflush(fp); rewind(fp); start = ftell(fp); return (fseek(fp, 0L, SEEK_END) - start); } 

Any ideas what I'm doing wrong here?

+4
source share
3 answers

Do

 fseek(fp, 0L, SEEK_END); return (ftell(fp) - start); 

instead

 return (fseek(fp, 0L, SEEK_END) - start); 

because fseek returns zero on success, not the offset as you expect here.

+3
source

A few comments:

  • do not call fflush() - your thread may be a read stream, for which fflush() causes undefined behavior

  • you have no mistakes!

  • fseek() returns 0 for success - you need to call ftell() to get the length

Change the code:

 long fileSize(FILE *fp) { fseek(fp, 0L, SEEK_END); return ftell(fp); } 
+1
source

You need to call ftell after fseek . Try:

 long fileSize(FILE *fp){ long start; fflush(fp); rewind(fp); start = ftell(fp); fseek(fp, 0L, SEEK_END); return ftell(fp); } 

There is no need to make a difference, so your first ftell useless and you can get rid of it. I would use:

 long filezise(FILE *fp) { fseek(fp,OL,SEEK_END); // fseek(f, 0, SEEK_SET); - only if you want to seek back to the beginning return ftell(fp); } 

Also, make sure you open the file in binary mode.

0
source

Source: https://habr.com/ru/post/1305296/


All Articles