Search code examples
cfilefile-iosystem-callsfile-descriptor

C — Why «write» can't write in file?


I want to deal with write: why doesn't it write to a file (errno 9, EBADF: Bad file descriptor), although if you replace fdOut with 1, then everything is perfectly displayed on the screen?

#include <stdio.h>
#include <fcntl.h>
#include <errno.h>

int main (void)
{
    int     fdOut;
    char    *outFileName = "out";
    char    sample[7] ="sample\0";
    
    fdOut = open (outFileName, O_CREAT, 0777);
    if (fdOut == -1)
        printf ("ups, errno %d\n", errno);
    else
    {
            write (fdOut, sample, 7);
            write (fdOut, "\n", 1);
    }
    close (fdOut);
    printf ("%s", sample);
    return (0);
}

Solution

  • Looking at the documentation of open (e.g. here), we see:

    The argument flags must include one of the following access modes: O_RDONLY, O_WRONLY, or O_RDWR. These request opening the file read-only, write-only, or read/write, respectively.

    It's safe to assume that you want O_WRONLY in this case:

    fdOut = open (outFileName, O_CREAT | O_WRONLY, 0777);
    

    You may also want to look into O_TRUNC for cases where the file does exist.