C 庫 - fread() 函式



C 庫的 size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) 函式從給定的流中讀取資料到由 ptr 指向的陣列中。它通常用於讀取二進位制檔案,但也可以用於讀取文字檔案。

語法

以下是 C 庫 fread() 函式的語法:

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

引數

此函式接受三個引數:

  • ptr: 指向一個記憶體塊的指標,讀取的資料將儲存在此記憶體塊中。
  • size: 要讀取的每個元素的大小(以位元組為單位)。
  • nmemb: 要讀取的元素數量,每個元素的大小為 size 位元組。
  • stream: 指向 FILE 物件的指標,該物件指定一個輸入流。

返回值

該函式返回成功讀取的元素數量,如果發生讀取錯誤或檔案結束 (EOF),則該數量可能小於 nmemb。如果 size 或 nmemb 為零,則 fread 返回零,並且 ptr 指向的記憶體內容保持不變。

示例 1:從二進位制檔案讀取整數陣列

該程式從二進位制檔案讀取一個包含 5 個整數的陣列,並列印每個整數。

以下是 C 庫 fread() 函式的示例。

#include <stdio.h>

int main() {
   FILE *file;
   int numbers[5];
   
   file = fopen("numbers.bin", "rb");
   if (file == NULL) {
       perror("Error opening file");
       return 1;
   }

   size_t result = fread(numbers, sizeof(int), 5, file);
   if (result != 5) {
       perror("Error reading file");
   } else {
       for (int i = 0; i < 5; i++) {
           printf("Number %d: %d\n", i + 1, numbers[i]);
       }
   }
   
   fclose(file);
   return 0;
}

輸出

以上程式碼產生以下結果:

Number 1: 1
Number 2: 2
Number 3: 3
Number 4: 4
Number 5: 5

示例 2:從二進位制檔案讀取結構體

該程式從二進位制檔案讀取一個 Employee 結構體,並列印其成員。

#include <stdio.h>

typedef struct {
   int id;
   char name[20];
   float salary;
} Employee;

int main() {
   FILE *file;
   Employee emp;
   
   file = fopen("employee.bin", "rb");
   if (file == NULL) {
       perror("Error opening file");
       return 1;
   }

   size_t result = fread(&emp, sizeof(Employee), 1, file);
   if (result != 1) {
       perror("Error reading file");
   } else {
       printf("Employee ID: %d\n", emp.id);
       printf("Employee Name: %s\n", emp.name);
       printf("Employee Salary: %.2f\n", emp.salary);
   }
   
   fclose(file);
   return 0;
}

輸出

執行以上程式碼後,我們將得到以下結果:

Employee ID: 101
Employee Name: John Doe
Employee Salary: 55000.00
廣告