函數原型
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);
疑問
讀取和寫入的總字節數=size*nmemb,那麼size和nmemb值的順序是否可以任意調換,比如:
ret=fread(buf, 1, 100, r_fd);
和
ret=fread(buf, 100, 1, r_fd);
以及
ret=fread(buf, 2, 50, r_fd);
他們之間有什麼差別?
返回值
On success, 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和fwrite返回讀到和寫入的塊數量(<=nmemb),當size等於1時,寫入的塊數量即爲寫入的字節數,否則,寫入的字節數=塊數量*size;
所以通常我們需要通過比較fread和fwrite返回值來判斷讀寫操作是否成功以及實際讀取和寫入的數量時,將size值設爲1,將nmemb設爲目標字節數。