自制fstat获取文件大小,总是返回0长度
我正在尝试使用我自己的函数从文件中获取文件大小。我将使用它为数据结构分配内存以保存文件信息。
文件大小函数如下所示:
long fileSize(FILE *fp){
long start;
fflush(fp);
rewind(fp);
start = ftell(fp);
return (fseek(fp, 0L, SEEK_END) - start);
}
你知道我在这里做错了什么吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这样做
而不是
因为 fseek 在成功时返回零,而不是像你这样的偏移量期待在这里。
Do
instead of
because fseek return zero on success not the offset as you are expecting here.
一些评论:
不要调用
fflush()
- 您的流可能是读取流,fflush()
会导致未定义的行为您没有任何错误检查!
fseek()
成功返回 0 - 您需要调用ftell()
来获取长度将代码更改为:
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 lengthChange the code to this:
您需要在
fseek
之后调用ftell
。尝试:没有必要做任何改变,所以你的第一个
ftell
是无用的,你可以摆脱它。我会使用:另外,请确保以二进制模式打开文件。
You need to call
ftell
afterfseek
. Try:There's no need to do a difference, so your first
ftell
is useless and you can get rid of it. I would use:Also, make sure you open your file in binary mode.