目录
前言
在 C 语言中,文件操作是通过 stdio.h 头文件中的 *文件指针(FILE ) 进行的。C 语言支持对文件的 读、写、追加 等操作,允许程序在磁盘上存储和读取数据。
一、文件操作的基本步骤
C 语言的文件操作一般分为以下几个步骤:
1. 打开文件(fopen)
2. 读写文件(fscanf、fprintf、fread、fwrite)
3. 关闭文件(fclose)
1.文件打开和关闭
打开文件 (fopen)
FILE *fopen(const char *filename, const char *mode);
mode 取值:
"r" 只读模式,文件必须存在
"w" 只写模式,文件不存在会创建,存在会清空
"a" 追加模式,在文件末尾写入数据
"r+" 读写模式,文件必须存在
"w+" 读写模式,文件不存在会创建,存在会清空
"a+" 读写模式,数据只能追加到文件末尾
示例:
FILE *fp = fopen("test.txt", "w");
if (fp == NULL) {
printf("文件打开失败!\n");
return 1;
}
关闭文件 (fclose)
int fclose(FILE *fp);
示例:
fclose(fp);
2.文件写入
文本写入 (fprintf)
fprintf(fp, "Hello, world!\n");
二进制写入 (fwrite)
fwrite(&data, sizeof(data), 1, fp);
3.文件读取
文本读取 (fscanf、fgets)
char str[100];
fscanf(fp, "%s", str);
或
fgets(str, 100, fp);
二进制读取 (fread)
fread(&data, sizeof(data), 1, fp);
4.文件指针移动 (fseek 和 ftell)
fseek(fp, 0, SEEK_END); // 移动到文件末尾
long size = ftell(fp); // 获取当前位置(文件大小)
rewind(fp); // 回到文件开头
5.文件操作示例:简易通讯录
#include <stdio.h>
#include <stdlib.h>
struct Contact {
char name[50];
char phone[20];
};
int main() {
FILE *fp = fopen("contacts.txt", "a+");
if (!fp) {
printf("无法打开文件!\n");
return 1;
}
struct Contact contact;
printf("输入联系人姓名: ");
scanf("%s", contact.name);
printf("输入联系人电话: ");
scanf("%s", contact.phone);
fprintf(fp, "%s %s\n", contact.name, contact.phone);
fclose(fp);
printf("联系人已保存!\n");
return 0;
}
总结
fopen 用于打开文件,记得 fclose
fprintf 和 fscanf 处理文本文件
fwrite 和 fread 处理二进制文件
fseek 和 ftell 操作文件指针