Monday, February 21, 2011

Homemade fstat to get file size, always return 0 length.

Hello, 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?

From stackoverflow
  • 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.

    Fred : Thank you. *I guess I should have spent some more time reading the man page. :)
  • 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);
    }
    
    Fred : Good suggestions, I'll take them with me. Thank you.
  • 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.

    Fred : Thats great, I did not know you could do this. Thanks!

0 comments:

Post a Comment