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

时间:2014-08-21 16:31:48

标签: c file

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) ..它也不会向文件写入任何内容。

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

1 个答案:

答案 0 :(得分:1)

在您发布的代码中,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