C语言如何将数据输入到txt文件
时间: 2023-06-19 09:10:22 浏览: 216
在C语言中,可以使用标准库函数fopen()和fprintf()将数据写入到txt文件中。具体操作步骤如下:
1. 打开txt文件,可以使用fopen()函数,该函数的语法如下:
```c
FILE *fopen(const char *filename, const char *mode);
```
filename:要打开的文件路径及文件名。
mode:文件打开的模式,如"r"表示只读模式,"w"表示写入模式(会清空文件内容),"a"表示追加模式。
例如,如果要以写入模式打开文件test.txt,可以使用以下代码:
```c
FILE *fp;
fp = fopen("test.txt", "w");
```
2. 使用fprintf()函数写入数据,该函数的语法如下:
```c
int fprintf(FILE *stream, const char *format, ...);
```
stream:指定写入数据的文件指针。
format:格式化字符串,用于指定写入数据的格式。
例如,如果要将一个整数写入文件中,可以使用以下代码:
```c
int num = 100;
fprintf(fp, "%d", num);
```
3. 关闭文件,可以使用fclose()函数,该函数的语法如下:
```c
int fclose(FILE *stream);
```
stream:要关闭的文件指针。
例如,如果要关闭文件test.txt,可以使用以下代码:
```c
fclose(fp);
```
完整的示例代码如下:
```c
#include <stdio.h>
int main()
{
FILE *fp;
int num = 100;
fp = fopen("test.txt", "w");
fprintf(fp, "%d", num);
fclose(fp);
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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_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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)