這個問題很容易搞錯,並導致很多問題,需要強調的是fread函數返回的並不是字節數。
realRead = fread(buf,item,count,fp) (每次讀item大小的數據塊,分count次來讀。)
而是返回的是成功有效的讀取的item元素的個數,而成功讀入的字節數則是realRead * sizeof(item)
一般說來realRead 是小於count的,很巧的情況就剛好為count.除非文件大小剛好為item大小的整數倍。
返回的是真實讀入item元素的個數,雖然讀了count次,但是真正讀到的有效個數為realRead個
真實讀入字節數就為realRead*sizeof(item)
RETURN VALUE
fread and fwrite return the number of items successfully read or written (i.e., not the number of
characters). If an error occurs, or the end-of-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(從文件流讀取數據)
表頭文件 #include<stdio.h>
定義函數 size_t fread(void * ptr,size_t size,size_t count,FILE * stream);
函數說明 fread()用來從文件流中讀取數據。參數stream為已打開的文件指針,參數ptr 指向欲存放讀取進來的數據空間,讀取的字節數以參數size*count來決定。
Fread()會返回實際讀取到的count數目,如果此值比參數count來得小,則代表可能讀到了文件尾了或者有錯誤發生(前者幾率大),這時必須用feof()或ferror()來決定發生什么情況。
返回值 返回實際讀取到的count數目。
fread返回的不是字節數,
當且僅當下面這么用的時候,返回值才是字節數(當然因為恰好一個數據塊大小為1個字節,相當於realRead*1)
char buff[size];
FILE *fp;
...
realRead = fread(buff, 1, size, fp);
...
如果是: fread(buff, size, 1, fp)
返回1表示讀取了size字節,返回0表示讀取數量不夠size字節
