gpt4 book ai didi

c - 在c中将字符串数组写入文件

转载 作者:行者123 更新时间:2023-11-30 21:03:21 24 4
gpt4 key购买 nike

int f = open("/tmp/vars.txt", O_RDWR | O_CREAT, S_IRUSR | S_IRGRP | S_IROTH);

if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
write(f, string_array, 100); //doesnt work

我也尝试过

FILE *f = fopen(vars.txt, "wb") //and 'w"
fprintf(f, "array = %s ", string_array);

没有打印任何内容

我已经很久没有使用C语言了。任何人都可以帮忙吗?

即使我仅用文本替换 string_array .. write(f, "test", 10) .. 它不会向文件写入任何内容。

已解决我遇到了缓冲区问题..我修复了它。

最佳答案

在您发布的代码中,open(2)创建(感谢 O_CREAT 标志)一个文本文件,但未正确设置其写入权限。尝试将其替换为:

int f = open("/tmp/vars.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);

此外,当写入完成后,您应该close(2)文件描述符:

if (close(f) < 0) {
perror("close");
exit(1);
}
<小时/>

此外,open(2)出错时不会返回 NULL。因此您应该检查 -1

关于c - 在c中将字符串数组写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25431395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com