C语言文件操作

时游大约 2 分钟

C 语言文件操作

配套Demo:codes/06_文件操作.c

文件指针与打开关闭

C 语言通过 FILE * 文件指针操作文件:

#include <stdio.h>

FILE *fp = fopen("data.txt", "w");   // 打开文件,失败返回 NULL
if (fp == NULL) {
    perror("文件打开失败");           // 打印错误原因
    return -1;
}
/* ... 读写操作 ... */
fclose(fp);                          // 用完必须关闭,否则可能丢数据

打开模式

模式含义文件不存在时文件存在时
"r"只读返回 NULL从头读
"w"只写创建新文件清空原内容
"a"追加写创建新文件在末尾追加
"r+"读写返回 NULL从头读写
"w+"读写创建新文件清空原内容
"a+"读 + 追加写创建新文件末尾追加
"rb" / "wb" ...二进制模式同上同上

读写函数

字符级:fputc / fgetc

fputc('A', fp);              // 写入一个字符
int c = fgetc(fp);           // 读取一个字符,读到末尾返回 EOF(-1)

字符串级:fputs / fgets

fputs("hello\n", fp);        // 写入一行字符串(不自动加换行)
char buf[100];
fgets(buf, sizeof(buf), fp); // 最多读 size-1 个字符,遇到换行或 EOF 停止

格式化:fprintf / fscanf

fprintf(fp, "%d %s %.2f\n", 1, "张三", 92.5);

int id;
char name[20];
float score;
fscanf(fp, "%d %s %f", &id, name, &score);

块读写:fwrite / fread(二进制常用)

// 写:把结构体数组一次性写入文件
Student stus[3] = {{1, "张三", 90}, {2, "李四", 85}, {3, "王五", 78}};
fwrite(stus, sizeof(Student), 3, fp);
// 参数:数据地址,单块大小,块数,文件指针

// 读:读回 3 个结构体
Student back[3];
fread(back, sizeof(Student), 3, fp);

完整Demo:学生成绩写入与读取

#include <stdio.h>

typedef struct
{
    int id;
    char name[20];
    float score;
} Student;

int main()
{
    // 1. 写入
    FILE *fp = fopen("students.txt", "w");
    if (fp == NULL) return -1;
    Student stus[2] = {{1, "张三", 92.5}, {2, "李四", 88.0}};
    for (int i = 0; i < 2; i++) {
        fprintf(fp, "%d %s %.1f\n", stus[i].id, stus[i].name, stus[i].score);
    }
    fclose(fp);

    // 2. 读取
    fp = fopen("students.txt", "r");
    if (fp == NULL) return -1;
    Student stu;
    printf("学号 姓名 成绩\n");
    while (fscanf(fp, "%d %s %f", &stu.id, stu.name, &stu.score) != EOF) {
        printf("%d %s %.1f\n", stu.id, stu.name, stu.score);
    }
    fclose(fp);
    return 0;
}

其他常用函数

feof(fp)        // 判断是否读到文件末尾(读到末尾返回非0)
rewind(fp)      // 将文件位置指针移回开头
fseek(fp, 0, SEEK_END)   // 移动位置:SEEK_SET 起点 / SEEK_CUR 当前 / SEEK_END 末尾
ftell(fp)       // 返回当前位置(配合 SEEK_END 可求文件大小)
remove("a.txt") // 删除文件
rename("a.txt", "b.txt") // 重命名

求文件大小

fseek(fp, 0, SEEK_END);
long size = ftell(fp);
rewind(fp);
Loading...