c语言文件读写操作代码
时间: 2023-08-01 12:09:55 浏览: 37
C语言文件读写操作可以使用标准库中的函数来实现,具体步骤如下:
1. 打开文件:使用fopen函数打开一个文件,并返回一个文件指针。
FILE *fp;
fp = fopen("file.txt", "r");
2. 读取文件:使用fscanf函数从文件中读取数据,可以使用循环读取直到文件结束。
char str[100];
while(fscanf(fp, "%s", str) != EOF){
printf("%s", str);
}
3. 写入文件:使用fprintf函数将数据写入文件,可以使用循环写入多条数据。
fprintf(fp, "%s %d", "hello", 123);
4. 关闭文件:使用fclose函数关闭文件。
fclose(fp);
完整的读写文件操作代码如下:
```
#include <stdio.h>
int main(){
FILE *fp;
char str[100];
// 打开文件
fp = fopen("file.txt", "r");
// 读取文件
while(fscanf(fp, "%s", str) != EOF){
printf("%s", str);
}
// 关闭文件
fclose(fp);
// 打开文件
fp = fopen("output.txt", "w");
// 写入文件
fprintf(fp, "%s %d", "hello", 123);
// 关闭文件
fclose(fp);
return 0;
}
```