File操作C语言实例有哪些?

99ANYc3cd6
预计阅读时长 25 分钟
位置: 首页 C语言 正文
  • fopen(): 打开文件
  • fclose(): 关闭文件
  • fprintf(), fscanf(): 格式化读写
  • fputs(), fgets(): 字符串读写
  • fputc(), fgetc(): 字符读写
  • fread(), fwrite(): 二进制块读写
  • fseek(), ftell(), rewind(): 文件指针操作

实例1:创建并写入文本文件 (使用 fprintf)

这个例子将创建一个名为 output.txt 的文件,并向其中写入几行文本。

代码 (write_text.c):

#include <stdio.h>
#include <stdlib.h> // 用于 exit 函数
int main() {
    // 1. 定义一个文件指针
    FILE *fp;
    // 2. 打开文件
    // "w" 表示写入模式 (Write)
    // 如果文件不存在,则创建;如果文件存在,则清空原有内容
    fp = fopen("output.txt", "w");
    // 3. 检查文件是否成功打开
    if (fp == NULL) {
        printf("无法创建或打开文件 output.txt\n");
        exit(1); // 异常退出程序
    }
    // 4. 向文件中写入格式化数据
    fprintf(fp, "Hello, C File I/O!\n");
    fprintf(fp, "This is the second line.\n");
    fprintf(fp, "The value of pi is approximately: %.2f\n", 3.14159);
    // 5. 关闭文件
    fclose(fp);
    printf("数据已成功写入 output.txt 文件,\n");
    return 0;
}

如何编译和运行:

gcc write_text.c -o write_text
./write_text

运行后,会生成 output.txt 文件,内容如下:

Hello, C File I/O!
This is the second line.
The value of pi is approximately: 3.14

实例2:读取并显示文本文件内容 (使用 fscanf)

这个例子将读取刚刚创建的 output.txt 文件,并将其内容打印到屏幕上。

代码 (read_text.c):

#include <stdio.h>
#include <stdlib.h>
int main() {
    FILE *fp;
    char buffer[100]; // 用于存储读取的行
    float pi_value;
    // 1. 打开文件
    // "r" 表示读取模式 (Read)
    // 文件必须已经存在,否则会打开失败
    fp = fopen("output.txt", "r");
    // 2. 检查文件是否成功打开
    if (fp == NULL) {
        printf("无法打开文件 output.txt\n");
        exit(1);
    }
    // 3. 从文件中读取数据
    // fgets 读取一行,直到遇到换行符或EOF
    printf("文件内容:\n");
    while (fgets(buffer, sizeof(buffer), fp) != NULL) {
        printf("%s", buffer); // 打印读取到的一行
    }
    // 将文件指针重置到文件开头
    rewind(fp);
    printf("\n--- 使用 fscanf 读取特定数据 ---\n");
    // fscanf 可以按格式读取
    while (fscanf(fp, "Hello, %s\n", buffer) == 1) { // 尝试匹配第一行
        printf("读取到问候语: %s\n", buffer);
    }
    fscanf(fp, "This is the second line.\n"); // 跳过第二行
    fscanf(fp, "The value of pi is approximately: %f\n", &pi_value);
    printf("读取到PI的值: %.2f\n", pi_value);
    // 4. 关闭文件
    fclose(fp);
    return 0;
}

如何编译和运行:

gcc read_text.c -o read_text
./read_text

预期输出:

Hello, C File I/O!
This is second line.
The value of pi is approximately: 3.14
--- 使用 fscanf 读取特定数据 ---
读取到问候语: C
读取到PI的值: 3.14

注意:fscanf 的匹配行为可能比预期复杂,上面的例子展示了它的基本用法。


实例3:追加内容到文本文件 (使用 fputs)

这个例子将在 output.txt 文件的末尾追加新的内容,而不是覆盖它。

代码 (append_text.c):

#include <stdio.h>
#include <stdlib.h>
int main() {
    FILE *fp;
    // "a" 表示追加模式 (Append)
    // 如果文件不存在,则创建;如果文件存在,则在末尾写入
    fp = fopen("output.txt", "a");
    if (fp == NULL) {
        printf("无法打开文件 output.txt 进行追加,\n");
        exit(1);
    }
    // 使用 fputs 写入一个字符串
    fputs("This line is appended at the end.\n", fp);
    fclose(fp);
    printf("内容已成功追加到 output.txt 文件,\n");
    return 0;
}

如何编译和运行:

gcc append_text.c -o append_text
./append_text

output.txt 的内容变为:

Hello, C File I/O!
This is the second line.
The value of pi is approximately: 3.14
This line is appended at the end.

实例4:二进制文件读写 (使用 fwritefread)

当需要处理结构体等复杂数据时,使用二进制模式更高效、更方便。

代码 (binary_rw.c):

#include <stdio.h>
#include <stdlib.h>
// 定义一个结构体
typedef struct {
    int id;
    char name[50];
    float score;
} Student;
int main() {
    FILE *fp;
    Student student1 = {101, "Zhang San", 95.5};
    Student student2 = {102, "Li Si", 88.0};
    Student read_student;
    // --- 写入二进制文件 ---
    fp = fopen("students.dat", "wb"); // "wb" 表示二进制写入模式
    if (fp == NULL) {
        printf("无法创建 students.dat 文件,\n");
        exit(1);
    }
    // 将结构体变量的地址和大小写入文件
    fwrite(&student1, sizeof(Student), 1, fp);
    fwrite(&student2, sizeof(Student), 1, fp);
    fclose(fp);
    printf("学生数据已以二进制格式写入 students.dat,\n");
    // --- 读取二进制文件 ---
    fp = fopen("students.dat", "rb"); // "rb" 表示二进制读取模式
    if (fp == NULL) {
        printf("无法打开 students.dat 文件,\n");
        exit(1);
    }
    printf("\n从文件中读取的学生数据:\n");
    while (fread(&read_student, sizeof(Student), 1, fp) == 1) {
        printf("ID: %d, Name: %s, Score: %.1f\n", read_student.id, read_student.name, read_student.score);
    }
    fclose(fp);
    return 0;
}

如何编译和运行:

gcc binary_rw.c -o binary_rw
./binary_rw

预期输出:

学生数据已以二进制格式写入 students.dat。
从文件中读取的学生数据:
ID: 101, Name: Zhang San, Score: 95.5
ID: 102, Name: Li Si, Score: 88.0

注意:students.dat 是一个二进制文件,用文本编辑器打开会显示乱码。


实例5:文件指针操作 (使用 fseek, ftell, rewind)

这个例子演示了如何在文件中移动指针、获取当前位置和重置指针。

代码 (file_seek.c):

#include <stdio.h>
#include <stdlib.h>
int main() {
    FILE *fp;
    char buffer[50];
    fp = fopen("output.txt", "r"); // 读取之前创建的文件
    if (fp == NULL) {
        printf("无法打开 output.txt,\n");
        exit(1);
    }
    // 1. ftell() 获取当前指针位置 (文件开头是 0)
    printf("初始指针位置: %ld\n", ftell(fp));
    // 2. fgets() 读取一行
    fgets(buffer, sizeof(buffer), fp);
    printf("读取第一行: %s", buffer);
    printf("读取一行后指针位置: %ld\n", ftell(fp));
    // 3. fseek() 移动指针
    // fseek(fp, offset, whence)
    // whence: SEEK_SET (文件开头), SEEK_CUR (当前位置), SEEK_END (文件末尾)
    // 移动到文件开头向后 10 个字节的位置
    fseek(fp, 10, SEEK_SET);
    printf("fseek后指针位置: %ld\n", ftell(fp));
    // 从当前位置再读取一行
    fgets(buffer, sizeof(buffer), fp);
    printf("从新位置读取: %s", buffer);
    // 4. rewind() 将指针重置到文件开头
    rewind(fp);
    printf("rewind后指针位置: %ld\n", ftell(fp));
    // 5. 移动到文件末尾
    fseek(fp, 0, SEEK_END);
    long file_size = ftell(fp); // 获取文件大小
    printf("文件大小 (字节): %ld\n", file_size);
    fclose(fp);
    return 0;
}

如何编译和运行:

gcc file_seek.c -o file_seek
./file_seek

预期输出 (基于 output.txt 的内容):

初始指针位置: 0
读取第一行: Hello, C File I/O!
读取一行后指针位置: 21
fseek后指针位置: 10
从新位置读取: C File I/O!
rewind后指针位置: 0
文件大小 (字节): 84

文件打开模式总结

模式 含义 如果文件不存在 如果文件存在
"r" 只读 报错 打开成功
"w" 只写 创建新文件 清空原有内容
"a" 追加 创建新文件 在末尾追加内容
"r+" 读写 报错 打开成功,指针在开头
"w+" 读写 创建新文件 清空原有内容
"a+" 读写 创建新文件 打开成功,指针在末尾
"rb", "wb", "ab" 二进制模式的读写/写/追加 同上 同上
"r+b", "w+b", "a+b" 二进制模式的读写/写/追加 同上 同上

希望这些实例能帮助你全面理解C语言的文件操作!

-- 展开阅读全文 --
头像
dede列表页标签如何正确调用?
« 上一篇 今天
织梦如何调用文章缩略标题?
下一篇 » 今天

相关文章

取消
微信二维码
支付宝二维码

目录[+]