fread
來自 cppreference.com
定義於標頭檔案 <stdio.h> |
||
(直到 C99) | ||
(C99 起) | ||
從給定的輸入流 stream 中讀取至多 count 個物件到陣列 buffer 中,如同透過為每個物件呼叫 fgetc size 次,並將結果按獲得的順序儲存到 buffer 的連續位置中,buffer 被重新解釋為 unsigned char 陣列。流的檔案位置指示器將前進讀取的字元數。
如果發生錯誤,流的檔案位置指示器的最終值是不確定的。如果讀取了部分元素,則其值是不確定的。
目錄 |
[編輯] 引數
buffer | - | 指向儲存讀取物件的陣列的指標 |
size | - | 每個物件的大小,以位元組為單位 |
count | - | 要讀取的物件數量 |
stream | - | 要讀取的流 |
[編輯] 返回值
成功讀取的物件數量,如果發生錯誤或到達檔案末尾,則可能小於 count。
如果 size 或 count 為零,fread
返回零且不執行其他操作。
fread
不區分檔案末尾和錯誤,呼叫者必須使用 feof 和 ferror 來確定發生了哪種情況。
[編輯] 示例
執行此程式碼
#include <stdio.h> enum { SIZE = 5 }; int main(void) { const double a[SIZE] = {1.0, 2.0, 3.0, 4.0, 5.0}; printf("Array has size %ld bytes, element size: %ld\n", sizeof a, sizeof *a); FILE *fp = fopen("test.bin", "wb"); // must use binary mode fwrite(a, sizeof *a, SIZE, fp); // writes an array of doubles fclose(fp); double b[SIZE]; fp = fopen("test.bin","rb"); const size_t ret_code = fread(b, sizeof b[0], SIZE, fp); // reads an array of doubles if (ret_code == SIZE) { printf("Array at %p read successfully, contents:\n", (void*)&a); for (int n = 0; n != SIZE; ++n) printf("%f ", b[n]); putchar('\n'); } else // error handling { if (feof(fp)) printf("Error reading test.bin: unexpected end of file\n"); else if (ferror(fp)) perror("Error reading test.bin"); } fclose(fp); }
可能的輸出
Array has size 40 bytes, element size: 8 Array at 0x1337f00d6960 read successfully, contents: 1.000000 2.000000 3.000000 4.000000 5.000000
[編輯] 參考
- C23 標準 (ISO/IEC 9899:2024)
- 7.21.8.1 fread 函式 (p: TBD)
- C17 標準 (ISO/IEC 9899:2018)
- 7.21.8.1 fread 函式 (p: 243-244)
- C11 標準 (ISO/IEC 9899:2011)
- 7.21.8.1 fread 函式 (p: 335)
- C99 標準 (ISO/IEC 9899:1999)
- 7.19.8.1 fread 函式 (p: 301)
- C89/C90 標準 (ISO/IEC 9899:1990)
- 4.9.8.1 fread 函式
[編輯] 另請參閱
(C11)(C11)(C11) |
從 stdin、檔案流或緩衝區讀取格式化輸入 (function) |
從檔案流獲取字元字串 (function) | |
寫入檔案 (function) | |
C++ 文件 關於 fread
|