Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 错误的文件描述符_C_File_Unix_File Descriptor - Fatal编程技术网

C 错误的文件描述符

C 错误的文件描述符,c,file,unix,file-descriptor,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) {

我正在学习文件描述符,并编写了以下代码:

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

}
#包括
#包括
#包括
#包括
int fdrd、fdwr、fdwt;
字符c;
main(int argc,char*argv[]){
如果((fdwt=open(“output”,O_CREAT,0777))=-1){
perror(“打开文件时出错:”);
出口(1);
}
字符c='x';
如果(写入(fdwt,&c,1)=-1){
perror(“写入文件时出错:”);
}
关闭(fdwt);
出口(0);
}
,但我得到:
写入文件时出错::错误的文件描述符


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

我认为光靠
O\u create
是不够的。尝试将
O_WRONLY
作为标志添加到打开命令。

尝试以下操作:

open("output", O_CREAT|O_WRONLY, 0777)
根据打开的(2)手册页:

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


是的,正如其他人所建议的,请将您的
open
更改为
open(“output”,O|u CREAT | O_WRONLY,0777))。如果需要读取文件,请使用
O_RDWR
。您可能还需要
O\u TRUNC
——有关详细信息,请参阅手册页。

Wow!太快了!:)成功了!现在我必须找出原因!多谢各位@露西-它给了你一个文件描述符,所以打开没有失败。。。但是描述符无法写入。您能否解释为什么需要O_WRONLY,以及0777来自何处?从open()返回时fdwt的val是多少?它应该是一个小整数,比如小于5。事实上,因为此代码中没有打开其他FD,所以它应该是3(即STDERR+1)。这些变量不需要是全局变量(很少有全局变量),您应该在
main
中声明它们。您还声明了两次
c
,第二次不需要
charc
中的
char
。同时,在函数中间的第二个声明<代码> C <代码>仅在C99中有效,但是您声明“代码>主< /代码>没有返回类型——这在C99中无效,它消除了C89和C的早期版本中存在的“隐式INT”规则。有些人会抛出错误并拒绝编译。你应该接受答案!