简体   繁体   中英

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

Looking at the documentation of open (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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