Bad file descriptor

84,377

Solution 1

Try this:

open("output", O_CREAT|O_WRONLY, 0777)

Solution 2

I think O_CREAT alone is not enough. Try adding O_WRONLY as flag to the open command.

Solution 3

According to the open(2) man page:

The argument flags must include one of the following access modes: O_RDONLY, O_WRONLY, or O_RDWR.

So yes, as suggested by others, please change your open to open("output", O_CREAT|O_WRONLY, 0777));. Use O_RDWR if you need to read from the file. You may also want O_TRUNC -- see the man page for details.

Share:
84,377
Lucy
Author by

Lucy

Updated on March 17, 2020

Comments

  • Lucy
    Lucy about 4 years

    I'm learning about file descriptors and I wrote this code:

    #include <unistd.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <fcntl.h>
    
    int fdrd, fdwr, fdwt;
    char c;
    
    main (int argc, char *argv[]) {
    
        if((fdwt = open("output", O_CREAT, 0777)) == -1) {
            perror("Error opening the file:");
            exit(1);
        }
    
        char c = 'x';
    
        if(write(fdwt, &c, 1) == -1) {
            perror("Error writing the file:");
        }
    
        close(fdwt);
        exit(0);
    
    }
    

    , but I'm getting: Error writing the file:: Bad file descriptor

    I don't know what could be wrong, since this is a very simple example.

  • Lucy
    Lucy almost 13 years
    Wow! So fast! :) That worked! Now I have to find out why! Thank you very much!
  • asveikau
    asveikau almost 13 years
    @Lucy - It gave you a file descriptor, so the open didn't fail ... but the descriptor was not valid for writing.
  • PyWalker2797
    PyWalker2797 about 4 years
    Could you explain why O_WRONLY is required, and where 0777 comes from?