c语言文件读写操作代码
时间: 2024-01-18 20:02:38 浏览: 22
以下是C语言中进行文件读写操作的代码示例:
文件读取:
```c
#include <stdio.h>
int main() {
FILE *fp;
int ch;
fp = fopen("example.txt", "r"); // 打开文件
if (fp == NULL) {
printf("无法打开文件\n");
return 1;
}
while ((ch = fgetc(fp)) != EOF) { // 逐个读取字符
putchar(ch);
}
fclose(fp); // 关闭文件
return 0;
}
```
文件写入:
```c
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("example.txt", "w"); // 打开文件
if (fp == NULL) {
printf("无法打开文件\n");
return 1;
}
fprintf(fp, "Hello world!"); // 写入内容
fclose(fp); // 关闭文件
return 0;
}
```
在进行文件读写操作时,需要注意以下几点:
- 在打开文件时,需要指定文件的访问模式(如只读模式`"r"`,只写模式`"w"`等)。
- 在使用`fgetc`读取文件时,需要检查读取的字符是否为文件结尾标记`EOF`,以避免无限循环。
- 在使用`fprintf`写入文件时,需要注意格式化字符串的使用方法,如`"%d"`表示输出整数,`"%s"`表示输出字符串等。
- 在完成文件读写操作后,需要使用`fclose`函数关闭文件,以释放文件句柄资源。