函式
<cstdio>

fread

size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
從流中讀取資料塊
中讀取一個包含 count 個元素的陣列,每個元素大小為 size 位元組,並將它們儲存在 ptr 指定的記憶體塊中。

流的位置指示器會按讀取的總位元組數向前移動。

如果成功,讀取的總位元組數為(size*count).

引數

ptr
指向一個大小至少為(size*count)位元組的記憶體塊的指標,轉換為一個void*.
size
要讀取的每個元素的大小(以位元組為單位)。
size_t 是一個無符號整數型別。
count
元素數量,每個元素的大小為 size 位元組。
size_t 是一個無符號整數型別。
stream
指向一個指定輸入流的 FILE 物件的指標。

返回值

返回成功讀取的元素總數。
如果這個數字與 count 引數不同,則說明在讀取時發生了讀取錯誤或到達了檔案末尾。在這兩種情況下,相應的指示器會被設定,可以分別用 ferrorfeof 進行檢查。
如果 sizecount 為零,函式返回零,並且流的狀態和 ptr 指向的內容都保持不變。
size_t 是一個無符號整數型別。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/* fread example: read an entire file */
#include <stdio.h>
#include <stdlib.h>

int main () {
  FILE * pFile;
  long lSize;
  char * buffer;
  size_t result;

  pFile = fopen ( "myfile.bin" , "rb" );
  if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

  // obtain file size:
  fseek (pFile , 0 , SEEK_END);
  lSize = ftell (pFile);
  rewind (pFile);

  // allocate memory to contain the whole file:
  buffer = (char*) malloc (sizeof(char)*lSize);
  if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

  // copy the file into the buffer:
  result = fread (buffer,1,lSize,pFile);
  if (result != lSize) {fputs ("Reading error",stderr); exit (3);}

  /* the whole file is now loaded in the memory buffer. */

  // terminate
  fclose (pFile);
  free (buffer);
  return 0;
}

此程式碼將myfile.bin載入到一個動態分配的記憶體緩衝區中,該緩衝區可用於將檔案內容作為一個數組來操作。

另見