我正在尝试使用我自己的函数从文件中获取文件大小。我将使用它来为数据结构分配内存以保存文件上的信息。
文件大小函数如下所示:
long fileSize(FILE *fp){
long start;
fflush(fp);
rewind(fp);
start = ftell(fp);
return (fseek(fp, 0L, SEEK_END) - start);
}
有什么想法我在这里做错了吗?
做
fseek(fp, 0L, SEEK_END);
return (ftell(fp) - start);
代替
return (fseek(fp, 0L, SEEK_END) - start);
因为fseek在成功时返回零,而不是您在这里期望的偏移量。
几点评论:
不要调用fflush()
- 您的流可能是读取流,这fflush()
会导致未定义的行为
你没有任何错误检查!
fseek()
成功返回 0 - 您需要调用ftell()
以获取长度
将代码更改为:
long fileSize(FILE *fp)
{
fseek(fp, 0L, SEEK_END);
return ftell(fp);
}
您需要在ftell
之后调用fseek
。尝试:
long fileSize(FILE *fp){
long start;
fflush(fp);
rewind(fp);
start = ftell(fp);
fseek(fp, 0L, SEEK_END);
return ftell(fp);
}
没有必要改变,所以你的第一个ftell
是没用的,你可以摆脱它。我会使用:
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);
}
另外,请确保以二进制模式打开文件。