开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜