C语言文件操作
在C语言中,文件操作功能使得程序可以处理外部数据文件,包括文本文件、CSV文件和二进制文件。通过标准库中的文件操作函数,我们可以进行文件的读取、写入和修改。下面将介绍C语言的文件操作,涵盖不同类型文件的处理方法。
一、文件操作的基本步骤
在C语言中,处理文件通常遵循以下步骤:
- 打开文件:使用
fopen函数,指定文件路径和模式(例如"r"、"w")。 - 文件读写:根据需求使用
fread、fwrite、fscanf、fprintf等函数。 - 关闭文件:使用
fclose函数释放资源。
二、文本文件操作
文本文件是一种常见的数据文件类型,通常以.txt为扩展名。文本文件操作包括读取和写入文本数据。
1、打开文件
FILE *fopen(const char *filename, const char *mode);
- 模式:
"r":只读模式,文件必须存在。"w":写模式,若文件不存在会创建,存在则清空内容。"a":追加模式,将内容写入文件末尾。
2、写入文本文件
示例代码:写入文本文件
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "w");
if (file == NULL) {
printf("无法打开文件。\n");
return 1;
}
fprintf(file, "Hello, World!\n");
fprintf(file, "C语言文件操作示例。\n");
fclose(file);
return 0;
}
3、读取文本文件
示例代码:读取文本文件
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("无法打开文件。\n");
return 1;
}
char line[100];
while (fgets(line, sizeof(line), file) != NULL) {
printf("%s", line);
}
fclose(file);
return 0;
}
二、CSV文件操作
CSV文件(逗号分隔值文件)是一种常用于存储表格数据的文件格式。通常以.csv为扩展名,CSV文件中每行代表一条记录,每个字段之间用逗号分隔。
1、写入CSV文件
示例代码:写入CSV文件
#include <stdio.h>
int main() {
FILE *file = fopen("data.csv", "w");
if (file == NULL) {
printf("无法打开文件。\n");
return 1;
}
// 写入表头
fprintf(file, "ID,Name,Score\n");
// 写入数据行
fprintf(file, "1,Alice,88.5\n");
fprintf(file, "2,Bob,92.0\n");
fclose(file);
return 0;
}
2、读取CSV文件
示例代码:读取CSV文件
#include <stdio.h>
int main() {
FILE *file = fopen("data.csv", "r");
if (file == NULL) {
printf("无法打开文件。\n");
return 1;
}
char line[100];
while (fgets(line, sizeof(line), file) != NULL) {
int id;
char name[50];
float score;
// 解析每行数据
sscanf(line, "%d,%49[^,],%f", &id, name, &score);
printf("ID: %d, Name: %s, Score: %.2f\n", id, name, score);
}
fclose(file);
return 0;
}
三、二进制文件操作
二进制文件用于存储结构化数据(如结构体)而无需文本编码。二进制文件的读写操作直接处理内存中的数据,而非文本。
1、写入二进制文件
示例代码:写入二进制文件
#include <stdio.h>
typedef struct {
int id;
char name[50];
float score;
} Student;
int main() {
FILE *file = fopen("data.bin", "wb");
if (file == NULL) {
printf("无法打开文件。\n");
return 1;
}
Student student = {1, "Alice", 88.5};
fwrite(&student, sizeof(Student), 1, file);
fclose(file);
return 0;
}
2、读取二进制文件
示例代码:读取二进制文件
#include <stdio.h>
typedef struct {
int id;
char name[50];
float score;
} Student;
int main() {
FILE *file = fopen("data.bin", "rb");
if (file == NULL) {
printf("无法打开文件。\n");
return 1;
}
Student student;
fread(&student, sizeof(Student), 1, file);
printf("ID: %d, Name: %s, Score: %.2f\n", student.id, student.name, student.score);
fclose(file);
return 0;
}
四、文件操作中的常用函数
fopen:打开文件。fclose:关闭文件。fgetc:从文件中读取一个字符。fputc:向文件写入一个字符。fgets:从文件中读取一行。fputs:向文件写入一行。fread:从文件中读取数据块(二进制)。fwrite:向文件中写入数据块(二进制)。fprintf:将格式化输出写入文件。fscanf:从文件中读取格式化输入。feof:判断文件是否结束。
五、小结
C语言的文件操作为数据的持久化提供了强大的工具。无论是简单的文本文件、结构化的CSV文件,还是高效的二进制文件,都可以通过C语言的标准库函数进行灵活的操作。
5906

被折叠的 条评论
为什么被折叠?



