在 C 語言中,鍵盤、顯示器、打印機、磁盤等邏輯設備均以「文件」形式統一管理。磁盤文件是編程中最常用的,C 提供兩套文件函數:
fopen, fclose, fread, fwrite, fprintf, fscanf, fgetc, fputc, fgets, fputs, fseek, ftell, rewind, feof, ferror。open, close, read, write, lseek(需 fcntl.h, io.h)。FILE *fopen(const char *filename, const char *mode);
int fclose(FILE *stream);
常用模式:
| 模式 | 含義 | 文件需存在 | 可讀/寫 |
|---|---|---|---|
| r | 只讀 | 是 | 讀 |
| w | 只寫(截斷/創建) | 否 | 寫 |
| a | 追加寫(創建) | 否 | 寫 |
| r+ | 讀寫 | 是 | 讀寫 |
| w+ | 讀寫(截斷/創建) | 否 | 讀寫 |
| a+ | 讀寫追加 | 否 | 讀寫 |
二進制模式在後加 b(如 rb, wb),Windows 下影響換行符轉換。
int fgetc(FILE *stream); // 讀一字符,EOF 表示結束/出錯
int fputc(int c, FILE *stream); // 寫一字符
char *fgets(char *s, int n, FILE *stream); // 讀 n-1 字符或換行/結束
int fputs(const char *s, FILE *stream); // 寫字符串(不含 \0)
int fprintf(FILE *stream, const char *format, ...);
int fscanf(FILE *stream, const char *format, ...);
類似 printf/scanf,多一個 FILE* 參數。
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
返回實際讀寫的項數(nmemb)。結構體/數組直接存取,極其高效。
int fseek(FILE *stream, long offset, int whence); // whence: SEEK_SET/CUR/END
long ftell(FILE *stream); // 返回當前位置
void rewind(FILE *stream); // 回到開頭
int feof(FILE *stream); // 結束標誌
int ferror(FILE *stream); // 錯誤標誌
void clearerr(FILE *stream);
#include
#include
#include
struct Student { int id; char name[20]; float score; };
int main() {
struct Student stu[3] = {{1, "Alice", 92.5}, {2, "Bob", 87}, {3, "Charlie", 95}};
FILE *fp = fopen("students.dat", "wb");
if (!fp) { perror("fopen"); return 1; }
fwrite(stu, sizeof(struct Student), 3, fp);
fclose(fp);
fp = fopen("students.dat", "rb");
struct Student read_stu[3];
fread(read_stu, sizeof(struct Student), 3, fp);
for (int i = 0; i < 3; ++i)
printf("%d %s %.1f\n", read_stu[i].id, read_stu[i].name, read_stu[i].score);
fclose(fp);
return 0;
}
fp == NULL,用 perror 打印原因。fread/fwrite 返回值 < 请求數表示結束或出錯,需配合 feof/ferror 判斷。fseek 偏移量不可靠(換行符轉換),二進制模式無此問題。fwrite,需序列化。fseeko/ftello(off_t 64 位)。