在C语言中,我们使用stdio.h库中的函数来操作文件。以下是一个简单的示例:
在这个例子中,我们首先使用fopen函数打开一个名为"test.txt"的文件,然后使用fgetc函数逐个字符地读取
文件的内容,直到达到文件的末尾(EOF)。最后,我们使用fclose函数关闭文件。
在C语言中,我们可以使用fputc或fprintf函数将数据写入文件。以下是一个简单的示例:
#include <stdio.h>
int main() {
FILE *file;
char ch;
// 打开文件
file = fopen("test.txt", "r");
if (file == NULL) {
printf("无法打开文件
");
return 1;
}
// 读取文件内容
while((ch = fgetc(file)) != EOF) {
putchar(ch);
}
// 关闭文件
fclose(file);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
int main() {
FILE *file;
char ch = 'A';
// 打开文件
file = fopen("test.txt", "w");
if (file == NULL) {
printf("无法打开文件
");
return 1;
}
// 写入文件
fputc(ch, file);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17