fopen:无效参数
fdopen: Invalid arguement
我正在尝试使用 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
是使用错误的权限创建的,它应该具有 read/write(?) 的权限。但是当 fdopen
使用模式 a+
调用文件描述符时,它会抛出错误,提示无效参数。
以a
模式成功打开。
导致此错误的模式 a
和 a+
之间究竟有何不同?
a+
模式表示append和read.
由于您最初以只写模式打开文件 (O_WRONLY | O_CREAT | O_EXCL
),读取访问与初始描述符的模式不兼容。
因此,对 fdopen() 的调用理所当然地失败了 EINVAL
。
我正在尝试使用 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
是使用错误的权限创建的,它应该具有 read/write(?) 的权限。但是当 fdopen
使用模式 a+
调用文件描述符时,它会抛出错误,提示无效参数。
以a
模式成功打开。
导致此错误的模式 a
和 a+
之间究竟有何不同?
a+
模式表示append和read.
由于您最初以只写模式打开文件 (O_WRONLY | O_CREAT | O_EXCL
),读取访问与初始描述符的模式不兼容。
因此,对 fdopen() 的调用理所当然地失败了 EINVAL
。