问题描述
当我使用fread(C语言)从文件中读取时,fread的返回值有时会为0.
when I read from a file using fread (C language), the return value of fread sometimes would be 0.
按照手册建议:
我必须编写这样的代码吗?
do I have to write code like this?
int bytes_read;
while((bytes_read = fread(buffer, sizeof(int), 1, fp)) == 0) {
}
我们是否总是需要检查fread或fwrite是否成功?
do we always have to check whether fread or fwrite succeeded?
推荐答案
不,如果 fread
或 fwrite
返回的内容较少,则没有必要进行这样的重试循环超出预期的读取或写入记录数.也就是说,stdio与可能导致短"读取或写入的低级 read
和 write
操作不同.
No, there's no sense in doing a retry-loop like this if fread
or fwrite
returns fewer than the expected number of records read or written. That is to say, stdio is not like the low-level read
and write
operations that can result in "short" reads or writes.
如果 fread
返回的记录少于请求的记录数,则说明您遇到了EOF或严重的读取错误.您可以通过检查 feof()
和 ferror()
来区分它们.
If fread
returns fewer than the requested number of records, you've either hit EOF or a serious read error. You can distinguish between them by checking feof()
and ferror()
.
类似地,如果 fwrite
返回的记录少于请求的记录数,则说明磁盘空间不足或出现严重的写入错误.
Similarly, if fwrite
returns fewer than the requested number of records, you've either run out of disk space or hit a serious write error.
在任何情况下,由于缓冲stdio使得基本上无法知道成功写入了多少,因此,如果遇到写入错误,通常需要考虑文件丢失并中止整个操作.
In any case, due to buffering stdio makes it essentially impossible to know how much was successfully written, so if you encounter a write error, you usually need to consider the file lost and abort the whole operation.
这篇关于fread和fwrite是否失败?如何处理呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!