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?
No, there’s no sense in doing a retry-loop like this if
freadorfwritereturns fewer than the expected number of records read or written. That is to say, stdio is not like the low-levelreadandwriteoperations that can result in “short” reads or writes.If
freadreturns fewer than the requested number of records, you’ve either hit EOF or a serious read error. You can distinguish between them by checkingfeof()andferror().Similarly, if
fwritereturns 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.