问题
when I read from a file using fread (C language), the return value of fread sometimes would be 0.
As manual suggested:
fread() and fwrite() return the number of items successfully read or written
do I have to write code like this?
int bytes_read;
while((bytes_read = fread(buffer, sizeof(int), 1, fp)) == 0) {
}
do we always have to check whether fread or fwrite succeeded?
回答1:
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.
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()
.
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.
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.
回答2:
http://pubs.opengroup.org/onlinepubs/000095399/functions/fread.html
Upon successful completion, fread() shall return the number of elements successfully read which is less than nitems only if a read error or end-of-file is encountered. If size or nitems is 0, fread() shall return 0 and the contents of the array and the state of the stream remain unchanged. Otherwise, if a read error occurs, the error indicator for the stream shall be set, and errno shall be set to indicate the error.
http://pubs.opengroup.org/onlinepubs/007904875/functions/fwrite.html
The fwrite() function shall return the number of elements successfully written, which may be less than nitems if a write error is encountered. If size or nitems is 0, fwrite() shall return 0 and the state of the stream remains unchanged. Otherwise, if a write error occurs, the error indicator for the stream shall be set,and errno shall be set to indicate the error
The ferror() or feof() functions must be used to distinguish between an error condition and an end-of-file condition.
回答3:
If fread fails, it will typically keep failing. Typically because it hit the end of file, but possibly for some other reason. If it fails, you would normally not try again.
回答4:
Yes.
The return value should always be count.
If it's not - you should use ferror()
or feof()
to determine whether you've reached the end of the file and/or encountered an error.
Ignoring errors and/or unexpected conditions is the stuff from which unreliable software is wrought down on unsuspecting users.
http://www.cplusplus.com/reference/clibrary/cstdio/fread/ <-- Junk
http://pubs.opengroup.org/onlinepubs/000095399/functions/fread.html
来源:https://stackoverflow.com/questions/9389669/do-fread-and-fwrite-have-failure-how-to-handle-this