C语言将数据写入txt文件代码
时间: 2023-04-05 13:00:36 浏览: 160
可以使用以下代码将数据写入txt文件:
```c
#include <stdio.h>
int main() {
FILE *fp;
char data[1000];
fp = fopen("data.txt", "w");
printf("请输入要写入文件的数据:\n");
fgets(data, 1000, stdin);
fprintf(fp, "%s", data);
fclose(fp);
printf("数据已成功写入文件!\n");
return 0;
}
```
这段代码会在程序所在目录下创建一个名为"data.txt"的文件,并将用户输入的数据写入该文件中。
相关问题
C语言按行写入txt文件代码
你可以使用以下代码将数据按行写入txt文件:
```c
#include <stdio.h>
int main() {
FILE *fp;
char str[100];
fp = fopen("data.txt", "w");
printf("请输入要写入文件的数据:\n");
while (fgets(str, 100, stdin) != NULL) {
fprintf(fp, "%s", str);
}
fclose(fp);
printf("数据已写入文件!\n");
return 0;
}
```
这段代码可以让用户输入数据,并将数据按行写入名为"data.txt"的文件中。
C语言如何将数据写入excel文件
C语言可以利用第三方库来将数据写入Excel文件。其中,常用的库有libxl、libxlsxwriter等。
以libxl为例,下面是一个简单的示例代码:
```c
#include <stdio.h>
#include "libxl.h"
int main()
{
BookHandle book = xlCreateBook();
SheetHandle sheet = xlBookAddSheet(book, "Sheet1", NULL);
// 写入数据
xlSheetWriteStr(sheet, 1, 1, "Hello", 0);
xlSheetWriteNum(sheet, 2, 1, 12345, 0);
// 保存Excel文件
if (xlBookSave(book, "example.xls")) {
printf("Excel file saved.\n");
} else {
printf("Failed to save Excel file.\n");
}
// 释放资源
xlBookRelease(book);
return 0;
}
```
在该示例代码中,我们首先创建一个名为"Sheet1"的工作表,然后在该工作表中写入了两个数据:"Hello"和12345。最后,我们通过调用`xlBookSave`函数将数据保存到名为"example.xls"的Excel文件中。
需要注意的是,在使用libxl库时,我们需要在编译时链接对应的库文件。例如,在Linux系统中,我们可以使用以下命令来编译上述示例代码:
```
gcc -o example example.c -lxl
```
其中,"-lxl"表示链接libxl库。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)