用C语言写一下文本文件读取和写入操作
时间: 2023-11-28 12:48:43 浏览: 45
文本文件读取操作:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
char buffer[1000];
fp = fopen("input.txt", "r");
if (fp == NULL) {
printf("Error: cannot open file\n");
exit(1);
}
while (fgets(buffer, 1000, fp) != NULL) {
printf("%s", buffer);
}
fclose(fp);
return 0;
}
```
文本文件写入操作:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
char buffer[1000];
fp = fopen("output.txt", "w");
if (fp == NULL) {
printf("Error: cannot open file\n");
exit(1);
}
printf("Enter text to write to file:\n");
fgets(buffer, 1000, stdin);
fprintf(fp, "%s", buffer);
fclose(fp);
return 0;
}
```
以上代码是简单的文本文件读取和写入操作,需要注意的是:
- 在打开文件时,需要判断文件是否成功打开,以防止 NULL 指针错误;
- 在使用 fgets 函数读取文件时,需要指定读取的最大字符数,避免缓冲区溢出;
- 在使用 fprintf 函数写入文件时,需要指定输出格式,如 `%s` 表示输出字符串。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)