| 函數 | 用途 |
|---|---|
| fopen | 開啟檔案,指定模式(讀/寫、二進制/文字) |
| fclose | 關閉檔案 |
| fread | 讀取資料 |
| fwrite | 寫入資料 |
| fseek/fsetpos | 移動檔案指標至任意位置 |
| ftell/fgetpos | 取得目前檔案指標位置 |
隨機存取意指可在檔案任意位置間跳轉讀寫,無需循序掃描。本文聚焦二進制檔案(位元組流),文字檔隨機存取較少用。
#include <stdio.h> <string.h>
int main() {
const char *filename = "test.txt";
const char *mytext = "Once upon a time there were three bears.";
FILE *ft = fopen(filename, "wb"); // 二進制寫入模式
if (ft) {
fwrite(mytext, sizeof(char), strlen(mytext), ft);
fclose(ft);
}
printf("len = %d", strlen(mytext));
return 0;
}
證明二進制檔案可存放文字資料,關鍵在於開啟模式 "wb"。
struct Record { int id; char name[32]; float score; };
Record recs[100];
FILE *fp = fopen("data.dat", "wb+");
// 寫入第 5 筆
fseek(fp, 4 * sizeof(Record), SEEK_SET);
fwrite(&recs[4], sizeof(Record), 1, fp);
// 讀取第 10 筆
fseek(fp, 9 * sizeof(Record), SEEK_SET);
fread(&recs[9], sizeof(Record), 1, fp);
fclose(fp);
利用 fseek 計算位移實現 O(1) 存取,適合資料庫索引、大型資料集處理。