我正在尝试用fopen和fdopen创建和打开一个文件来编写一些内容。下面是我编写的代码:
char Path[100];
int write_fd;
snprintf(Path,100,"%s/%s","/home/user","myfile.txt");
printf("opening file..\n");
write_fd = open(Path, O_WRONLY | O_CREAT | O_EXCL, 0777);
if(write_fd!=-1)
{
printf(" write_fd!=-1\n");
FILE *file_fp = fdopen(write_fd,"a+");
if (file_fp == NULL)
{
printf("Could not open file.File pointer error %s\n", std::strerror(errno));
close(write_fd);
return 0;
}
write(write_fd, "First\n", 7);
write(write_fd, "Second\n", 8);
write(write_fd, "Third\n", 7);
fclose(file_fp);
}文件fd write_fd是错误地使用权限创建的,该权限应该具有读取/写入(?)权限。但是,当fdopen用模式a+调用文件描述符时,它会抛出错误,说参数无效。
它成功地以模式a打开。
导致此错误的模式a和a+到底有什么不同?
发布于 2015-05-27 08:30:13
a+模式意味着附加和读取。
由于您最初是以只写模式(O_WRONLY | O_CREAT | O_EXCL)打开文件的,因此读取访问与初始描述符的模式不兼容。
因此,对fdopen()的调用在EINVAL中理所当然地失败了。
https://stackoverflow.com/questions/30476983
复制相似问题