C中文件读取fread和fwrite 返回值等注意事项
#include <stdio.h>
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
The function fread() reads nmemb items of data, each size bytes long, from the stream pointed to by stream, storing them at the location given by ptr.
译文:fread函数从stream指向的文件流中,读取nmemb个数据元素(nmemb这里我看成n个memory block 即内存块),每个元素size 字节长,并将这些数据存储到ptr指向的地址里面。
The function fwrite() writes nmemb items of data, each size bytes long, to the stream pointed to by stream, obtaining them from the location given by ptr.
译文:fwrite函数从ptr指向的地址里面获取nmemb个数据元素,每个size字节长,将这些数据存到stream指向的文件流中。
fread() and fwrite() return the number of items read or written. This number equals the number of bytes transferred only when size is 1. If an error occurs, or the end of the file is reached, the return value is a short item count (or zero).fread() does not distinguish between end-of-file and error, and callers must use feof(3) and ferror(3) to determine which occurred.
译文:fread和fwrite返回读取或写入的数据元素的个数。只有当size等于1的时候,返回的元素个数才与传输的字节数目相等。
如果发生错误,或者到达文件文件末尾,这个返回值就会小于nmemb(当最后一次读取或写入不够nmemb个数据元素时)或者甚至是0 fread函数并不区别是发生了错误还是到达文件尾,则这就需要调用者feof和ferror来判断是不是到达文件尾或者发生了错误
附注:看过两次 总觉得很有注意点 不小心容易出错 所以干脆写了这篇博文 以此告诫自己