简体   繁体   English

fdopen:无效的争论

[英]fdopen: Invalid arguement

I am trying to create and open a file with fopen and fdopen to write some content. 我正在尝试使用fopenfdopen创建并打开文件以写入一些内容。 Below is the code I wrote: 以下是我编写的代码:

    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);
   }

The file fd write_fd is created with the permissions WRONGLY which should have permission to read/write(?). 文件fd write_fd的创建具有错误权限,该权限应该具有读/写(?)权限。 But when fdopen called on the file descriptor with mode a+ , it is throwing error saying Invalid Argument. 但是,当fdopena+模式调用文件描述符时,它会抛出错误,提示Invalid Argument。

It is successfully opened with mode a . 它已使用模式a成功打开。

What exactly differs between the modes a and a+ that causes this error ? 导致此错误的模式aa+之间的确切区别是什么?

The a+ mode means append and read . a+模式表示追加读取

Since you have initially opened the file in write-only mode ( O_WRONLY | O_CREAT | O_EXCL ), read access is not compatible with the mode of the initial descriptor. 由于您最初是在只读模式下打开文件的( O_WRONLY | O_CREAT | O_EXCL ),因此读取访问权限与初始描述符的模式不兼容。

Therefore, the call to fdopen() rightfully fails with EINVAL . 因此,对fdopen()的调用正确地以EINVAL失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM