Reputation: 459
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?
Upvotes: 4
Views: 1406
Reputation: 212979
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);
}
Upvotes: 1
Reputation: 43467
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.
Upvotes: 0