c语言文件读写操作代码
时间: 2023-05-30 08:03:24 浏览: 88
文件读写操作是C语言中非常常见的操作之一,以下是基本的文件读写操作代码示例:
文件写入操作:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
char str[] = "Hello, world!";
fp = fopen("test.txt", "w");
if (fp == NULL) {
printf("File open error!\n");
exit(1);
}
fputs(str, fp);
fclose(fp);
return 0;
}
```
文件读取操作:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
char str[100];
fp = fopen("test.txt", "r");
if (fp == NULL) {
printf("File open error!\n");
exit(1);
}
fgets(str, 100, fp);
printf("Read from file: %s\n", str);
fclose(fp);
return 0;
}
```
以上代码演示了如何打开文件、写入数据、关闭文件、打开文件、读取数据、关闭文件的过程。需要注意的是,每次打开文件操作后需要及时关闭文件。