在 C 語言標準庫中,fread 是用於從檔案流讀取二進位資料的核心函數。它能夠高效地將指定數量、指定大小的資料元素從檔案流讀取到記憶體緩衝區中,是處理二進位檔案(如圖片、音訊、自定義結構體資料)不可或缺的工具。
size_t fread(void *buffer, size_t size, size_t count, FILE *stream);
size * count 位元組。fopen 回傳)。函數回傳實際成功讀取的元素個數(而非位元組數)。若回傳值小於 count,表示可能遇到檔案結尾(EOF)或發生讀取錯誤。此時應搭配 feof() 與 ferror() 進一步判斷具體原因:
feof(stream) 非零 → 已到達檔案結尾ferror(stream) 非零 → 發生讀取錯誤#include <stdio.h>
#include <string.h>
int main(void) {
FILE *stream;
char msg[] = "this is a test";
char buf[20];
/* 以 w+ 模式開啟:可讀寫,若檔案存在則截斷,否則建立 */
if ((stream = fopen("DUMMY.FIL", "w+")) == NULL) {
fprintf(stderr, "Cannot open output file.\n");
return 1;
}
/* 寫入資料:包含結尾的 null 字元 */
fwrite(msg, 1, strlen(msg) + 1, stream);
/* 將檔案指標移回開頭 */
fseek(stream, 0, SEEK_SET);
/* 讀取資料並顯示 */
fread(buf, 1, strlen(msg) + 1, stream);
printf("%s\n", buf);
fclose(stream);
return 0;
}
#include <stdio.h>
void main(void) {
FILE *stream;
char list[30];
int i, numread, numwritten;
/* 以文字模式開啟寫入 */
if ((stream = fopen("fread.out", "w+t")) != NULL) {
for (i = 0; i < 25; i++)
list[i] = (char)('z' - i); /* 填入 'z' 到 'a' */
numwritten = fwrite(list, sizeof(char), 25, stream);
printf("Wrote %d items\n", numwritten);
fclose(stream);
} else {
printf("Problem opening the file\n");
}
/* 以文字模式開啟讀取 */
if ((stream = fopen("fread.out", "r+t")) != NULL) {
numread = fread(list, sizeof(char), 25, stream);
printf("Number of items read = %d\n", numread);
printf("Contents of buffer = %.25s\n", list);
fclose(stream);
} else {
printf("File could not be opened\n");
}
}
size 為 sizeof(結構體類型),count 為元素個數。setvbuf 調整緩衝區大小以提升效能。