C语言文件读写 #

一、字符读写 #

1.1 fgetc和fputc #

c
#include <stdio.h>

int main() {
    FILE* fp = fopen("test.txt", "w");
    if (fp == NULL) return 1;
    
    fputc('A', fp);
    fputc('B', fp);
    fclose(fp);
    
    fp = fopen("test.txt", "r");
    int ch;
    while ((ch = fgetc(fp)) != EOF) {
        printf("%c", ch);
    }
    fclose(fp);
    return 0;
}

二、字符串读写 #

2.1 fgets和fputs #

c
#include <stdio.h>

int main() {
    FILE* fp = fopen("test.txt", "w");
    fputs("Hello\n", fp);
    fputs("World\n", fp);
    fclose(fp);
    
    fp = fopen("test.txt", "r");
    char buf[100];
    while (fgets(buf, sizeof(buf), fp) != NULL) {
        printf("%s", buf);
    }
    fclose(fp);
    return 0;
}

三、格式化读写 #

3.1 fprintf和fscanf #

c
#include <stdio.h>

int main() {
    FILE* fp = fopen("data.txt", "w");
    fprintf(fp, "%d %f %s\n", 10, 3.14, "Hello");
    fclose(fp);
    
    int a;
    float b;
    char c[20];
    fp = fopen("data.txt", "r");
    fscanf(fp, "%d %f %s", &a, &b, c);
    printf("%d %f %s\n", a, b, c);
    fclose(fp);
    return 0;
}

四、二进制读写 #

4.1 fread和fwrite #

c
#include <stdio.h>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    
    FILE* fp = fopen("data.bin", "wb");
    fwrite(arr, sizeof(int), 5, fp);
    fclose(fp);
    
    int buf[5];
    fp = fopen("data.bin", "rb");
    fread(buf, sizeof(int), 5, fp);
    fclose(fp);
    
    for (int i = 0; i < 5; i++) {
        printf("%d ", buf[i]);
    }
    printf("\n");
    return 0;
}

五、总结 #

函数 功能
fgetc/fputc 字符读写
fgets/fputs 字符串读写
fprintf/fscanf 格式化读写
fread/fwrite 二进制读写

下一步,让我们学习文件定位!

最后更新:2026-03-26