c语言文件读写操作代码
时间: 2023-08-01 09:09:01 浏览: 44
文件读写是C语言中非常基础和常用的操作,可以使用标准库函数来实现。下面是一个简单的文件读写的示例代码:
```c
#include <stdio.h>
int main() {
FILE *fp;
char str[100];
// 打开文件
fp = fopen("example.txt", "w+");
if(fp == NULL) {
printf("Failed to open file.\n");
return 1;
}
// 写入文件
fprintf(fp, "Hello World!");
// 读取文件
fseek(fp, 0, SEEK_SET);
fscanf(fp, "%s", str);
printf("Read from file: %s\n", str);
// 关闭文件
fclose(fp);
return 0;
}
```
在这个示例中,我们首先打开一个文件,并使用`fprintf()`函数将字符串"Hello World!"写入文件中。然后,我们使用`fseek()`函数将文件指针移至文件开头,并使用`fscanf()`函数将文件内容读取到一个字符数组中。最后,我们输出读取到的内容,并使用`fclose()`函数关闭文件。