【发布时间】:2011-09-08 21:12:21
【问题描述】:
我正在学习文件描述符,并编写了以下代码:
#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
我不知道哪里出了问题,因为这是一个非常简单的例子。
【问题讨论】:
-
从 open() 返回时 fdwt 的 val 是多少?它应该是一个小整数,比如小于5。实际上,由于这段代码中没有打开其他fd,它应该是3(即STDERR + 1)。
-
顺便说一下,您的代码有几个问题。这些变量不需要是全局的(很少有),你应该在
main中声明它们。您还声明了两次c,第二次不需要char c中的char。同时,函数中间的第二个c声明只在C99中有效,但是你声明main没有返回类型——在C99中无效,这就消除了“隐式int”规则存在于 C89 和 C 的早期版本中。大多数编译器应该为此发出警告,有些会抛出错误并拒绝编译。 -
你应该接受答案!
标签: c file unix file-descriptor