文件描述符错误

Luc*_*ucy 19 c unix file file-descriptor

我正在学习文件描述符,我写了这段代码:

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

}
Run Code Online (Sandbox Code Playgroud)

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

我不知道会出现什么问题,因为这是一个非常简单的例子.

小智 21

试试这个:

open("output", O_CREAT|O_WRONLY, 0777)
Run Code Online (Sandbox Code Playgroud)

  • @RedX:因为这是一个系统调用,我会选择`man 2 open`. (4认同)
  • @Lucy - 它给了你一个文件描述符,所以打开没有失败......但描述符对于写入无效。 (2认同)

Red*_*edX 8

我认为O_CREAT孤军奋战是不够的.尝试O_WRONLY在open命令中添加as flag.


spa*_*unt 8

根据open(2)手册页:

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

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