linux c之把最简单的字符串数据追加写入文件

1 问题

把最简单的字符串数据追加写入文件

2 代码实现

#include <stdio.h>
#include <string.h>

void write_data_to_file(const char *path, char *str)
{
FILE *fd = fopen(path, "a+");
if (fd == NULL)
{
printf("fd is NULL and open file fail\n");
return;
}
printf("fd != NULL\n");
if (str && str[0] != 0)
{
fwrite(str, strlen(str), 1, fd);
char *next = "\n";
fwrite(next, strlen(next), 1, fd);
}
fclose(fd);
}

int main()
{
char *path = "/home/chenyu/Desktop/linux/wf/c.txt";
char *str = "chenyu";
char *str1 = "hell word";
char *str2 = "write data to file";
write_data_to_file(path, str);
write_data_to_file(path, str1);
write_data_to_file(path, str2);
return 0;
}

3 运行结果

gcc -g write.c -o write
./write

vim c.txt

chenyu
hell word
write data to file
(0)

相关推荐