1. 程式人生 > >C語言fread()函式:讀檔案函式(從檔案流讀取資料)

C語言fread()函式:讀檔案函式(從檔案流讀取資料)

相關函式:fopen, fwrite, fseek, fscanf

標頭檔案:#include <stdio.h>

定義函式:size_t fread(void * ptr, size_t size, size_t nmemb, FILE * stream);

函式說明:fread()用來從檔案流中讀取資料. 

引數stream 為已開啟的檔案指標, 引數ptr 指向欲存放讀取進來的資料空間, 讀取的字元數以引數size*nmemb 來決定. Fread()會返回實際讀取到的nmemb 數目, 如果此值比引數nmemb 來得小, 則代表可能讀到了檔案的尾或有錯誤發生, 這時必須用feof()或ferror()來決定發生什麼情況.


返回值:返回實際讀取到的nmemb 數目。

範例
#include <stdio.h>
#define nmemb 3
struct test
{
    char name[20];
    int size;
} s[nmemb];

main()
{
    FILE * stream;
    int i;
    stream = fopen("/tmp/fwrite", "r");
    fread(s, sizeof(struct test), nmemb, stream);
    fclose(stream);
    for(i = 0; i < nmemb; i++)
        printf("name[%d]=%-20s:size[%d]=%d\n", i, s[i].name, i, s[i].size);

}

執行
name[0]=Linux! size[0]=6
name[1]=FreeBSD! size[1]=8
name[2]=Windows2000 size[2]=11