fwrite写字符串
时间: 2023-08-13 14:11:58 浏览: 94
您可以使用 `fwrite` 函数将字符串写入文件。下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
FILE *file = fopen("output.txt", "w");
if (file == NULL) {
printf("无法打开文件\n");
return 1;
}
fwrite(str, sizeof(char), strlen(str), file);
fclose(file);
printf("字符串已成功写入文件\n");
return 0;
}
```
在上述示例中,我们首先定义了一个字符数组 `str`,并将要写入的字符串赋值给它。
然后,我们使用 `fopen` 函数打开一个名为 "output.txt" 的文件,并指定以文本模式写入。如果文件打开失败,则会输出错误消息并终止程序。
之后,我们使用 `fwrite` 函数将字符数组 `str` 中的数据写入文件。该函数的参数依次为要写入的数据的指针(这里是数组名 `str`),每个数据的大小(`sizeof(char)`),要写入的数据长度(通过 `strlen` 函数获取),以及要写入的文件指针。
最后,我们使用 `fclose` 函数关闭文件,并输出一条成功写入的消息。
请注意,这里假设您要写入的是以 null 结尾的字符串。如果要写入的字符串不以 null 结尾,可以在 `fwrite` 函数之后使用 `fputc('\0', file)` 写入 null 字符。