文件描述符错误

时间:2011-06-05 19:57:17

标签: c file unix 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);

}

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

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

3 个答案:

答案 0 :(得分:21)

试试这个:

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

答案 1 :(得分:8)

我认为仅O_CREAT是不够的。尝试将O_WRONLY作为标志添加到open命令。

答案 2 :(得分:8)

根据open(2)手册页:

  

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

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