c语言文件读写操作代码
时间: 2024-01-17 17:05:37 浏览: 22
以下是一个简单的 C 语言程序示例,用于在文件中读取和写入数据:
```c
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char c;
/* 打开文件 */
fp = fopen("file.txt", "w+");
/* 写入数据 */
fputs("This is a test.", fp);
/* 将文件指针移到文件开头 */
rewind(fp);
/* 读取数据 */
while((c = fgetc(fp)) != EOF)
printf("%c", c);
/* 关闭文件 */
fclose(fp);
return 0;
}
```
在这个示例中,我们使用 `fopen()` 函数打开一个名为 "file.txt" 的文件,以进行读写操作。在文件中写入数据时,我们使用 `fputs()` 函数。然后,我们使用 `rewind()` 函数将文件指针移到文件开头,并使用 `fgetc()` 函数读取文件中的数据。最后,我们使用 `fclose()` 函数关闭文件。
请注意,此示例仅用于演示目的,实际应用程序需要添加错误处理和其他必要的功能。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)