简体   繁体   English

C — 为什么 «write» 不能写入文件?

[英]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?我想处理write :为什么它不写入文件(errno 9, EBADF: Bad file descriptor ),尽管如果将fdOut替换为1 ,那么一切都会完美地显示在屏幕上?

#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:查看open的文档(例如此处),我们看到:

The argument flags must include one of the following access modes : O_RDONLY , O_WRONLY , or O_RDWR .参数标志必须包括以下访问模式之一O_RDONLYO_WRONLYO_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:在这种情况下,可以安全地假设您想要O_WRONLY

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

You may also want to look into O_TRUNC for cases where the file does exist.您可能还想查看O_TRUNC以了解文件确实存在的情况。

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

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