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 whichfflush()
results in undefined behaviouryou don't have any error checking !
fseek()
returns 0 for success - you need to callftell()
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.
精彩评论