Search code examples
cfilefile-iobinaryfseek

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?


Solution

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