C语言 错误的文件描述符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6245477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:51:25  来源:igfitidea点击:

Bad file descriptor

cfileunixfile-descriptor

提问by Lucy

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

,但我得到: Error writing the file:: Bad file descriptor

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

我不知道有什么问题,因为这是一个非常简单的例子。

回答by patapizza

Try this:

尝试这个:

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

回答by RedX

I think O_CREATalone is not enough. Try adding O_WRONLYas flag to the open command.

我觉得O_CREAT光靠自己是不够的。尝试将O_WRONLYas 标志添加到 open 命令。

回答by spacehunt

According to the open(2) man page:

根据 open(2) 手册页:

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

参数标志必须包括以下访问模式之一:O_RDONLY、O_WRONLY 或 O_RDWR。

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

所以是的,正如其他人所建议的那样,请将您openopen("output", O_CREAT|O_WRONLY, 0777));. O_RDWR如果您需要从文件中读取,请使用。您可能还需要O_TRUNC- 有关详细信息,请参阅手册页。