fdopen: Invalid arguement

I am trying to create and open a file with fopen and fdopen to write some content.
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!=-1n");

       FILE *file_fp = fdopen(write_fd,"a+");

       if (file_fp == NULL)
       {
              printf("Could not open file.File pointer error %sn", std::strerror(errno));
              close(write_fd);
               return 0;         
       }
       write(write_fd, "Firstn", 7);
       write(write_fd, "Secondn", 8);
       write(write_fd, "Thirdn", 7);
       fclose(file_fp);
   }

The file fd “write_fd” is created with the permissions WRONLY which should have permission to read/write(?). But when fdopen called on the file descriptor with mode ‘a+’, it is throwing error saying Invalid Argument.

It is successfully opened with mode ‘a’.

What exactly differs between the modes ‘a’ and ‘a+’ that causes this error ?


Source: c++

Leave a Reply