c语言文件读写操作代码
时间: 2023-08-02 16:07:48 浏览: 32
以下是一个简单的示例代码,演示如何在C语言中进行文件读写操作:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
char str[1000], filename[100];
// 从用户输入中获取文件名
printf("请输入要读取的文件名:\n");
scanf("%s", filename);
// 尝试打开文件
fp = fopen(filename, "r");
// 如果文件打开失败,输出错误信息并退出程序
if (fp == NULL) {
printf("无法打开文件 %s\n", filename);
exit(EXIT_FAILURE);
}
// 读取文件内容并输出到控制台
while (fgets(str, 1000, fp) != NULL) {
printf("%s", str);
}
// 关闭文件
fclose(fp);
return 0;
}
```
该示例程序首先提示用户输入要读取的文件名,然后尝试打开该文件并读取其中的内容,最后输出到控制台。如果打开文件失败,程序会输出错误信息并退出。如果要进行写文件操作,只需要将 `fopen` 函数的第二个参数改为 "w" 或 "a" 即可,分别代表覆盖写和追加写。例如,要向文件中追加内容,可以使用以下代码:
```c
fp = fopen(filename, "a");
if (fp == NULL) {
printf("无法打开文件 %s\n", filename);
exit(EXIT_FAILURE);
}
fprintf(fp, "要追加的内容");
fclose(fp);
```
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)