简体   繁体   中英

Homemade fstat to get file size, always returns 0 length

I am trying to use my own function to get the file size from a file. I'll use this to allocate memory for a data structure to hold the information on the file.

The file size function looks like this:

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?

Do

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

instead of

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

because fseek return zero on success not the offset as you are expecting here.

A few comments:

  • don't call fflush() - your stream might be a read stream, for which fflush() results in undefined behaviour

  • you don't have any error checking !

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

Change the code to this:

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

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's no need to do a difference, so your first ftell is 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 your file in binary mode.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM