首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> C 語言基礎

C 語言基礎教程:標準文件輸入輸出函數詳解(fopen, fclose, fread, fwrite 等)

     編輯:C 語言基礎

文件操作概述

在 C 語言中,鍵盤、顯示器、打印機、磁盤等邏輯設備均以「文件」形式統一管理。磁盤文件是編程中最常用的,C 提供兩套文件函數:

  • 標準文件函數(緩衝型):ANSI C 標準,跨平台,帶緩衝區,效率高。核心函數:fopen, fclose, fread, fwrite, fprintf, fscanf, fgetc, fputc, fgets, fputs, fseek, ftell, rewind, feof, ferror。
  • 非標準文件函數(非緩衝型):源自 UNIX,直接系統調用,無緩衝,如 open, close, read, write, lseek(需 fcntl.h, io.h)。

標準文件函數核心詳解

1. 文件打開與關閉

FILE *fopen(const char *filename, const char *mode);
int fclose(FILE *stream);

常用模式:

模式含義文件需存在可讀/寫
r只讀是讀
w只寫(截斷/創建)否寫
a追加寫(創建)否寫
r+讀寫是讀寫
w+讀寫(截斷/創建)否讀寫
a+讀寫追加否讀寫

二進制模式在後加 b(如 rb, wb),Windows 下影響換行符轉換。

2. 字符輸入輸出

int fgetc(FILE *stream);        // 讀一字符,EOF 表示結束/出錯
int fputc(int c, FILE *stream); // 寫一字符

3. 行輸入輸出

char *fgets(char *s, int n, FILE *stream);  // 讀 n-1 字符或換行/結束
int fputs(const char *s, FILE *stream);     // 寫字符串(不含 \0)

4. 格式化輸入輸出

int fprintf(FILE *stream, const char *format, ...);
int fscanf(FILE *stream, const char *format, ...);

類似 printf/scanf,多一個 FILE* 參數。

5. 二進制塊讀寫(核心)

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)。結構體/數組直接存取,極其高效。

6. 隨機訪問

int fseek(FILE *stream, long offset, int whence);  // whence: SEEK_SET/CUR/END
long ftell(FILE *stream);                          // 返回當前位置
void rewind(FILE *stream);                         // 回到開頭

7. 狀態檢查

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;
}

避坑指南

  1. 打開失敗必須檢查 fp == NULL,用 perror 打印原因。
  2. fread/fwrite 返回值 < 请求數表示結束或出錯,需配合 feof/ferror 判斷。
  3. 文本模式下 fseek 偏移量不可靠(換行符轉換),二進制模式無此問題。
  4. 結構體含指針時不可直接 fwrite,需序列化。
  5. 大文件用 fseeko/ftello(off_t 64 位)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved