c - 文件描述符,open() 返回零

标签 c

我打开一个文件,想在里面写点东西。问题是 fd2 由于某种原因为 0。它不是写入文件,而是写入终端。我没有在我的代码中的任何地方关闭(0)。为什么我得到 fd = 0 而不是例如 3。在终端上写入的原因是 fd 的值为零?我知道 fd = 0 是标准输入,

有什么想法吗?谢谢你。

if ((fd2 = open(logFile, O_RDWR |O_APPEND | O_CREAT , 0666) == -1))
    DieWithError("open() failed");

printf("FD2 = %d",fd2);     //returns me zero

bzero(tempStr, sizeof(tempStr));
bzero(hostname, sizeof(hostname));

gethostname(hostname, sizeof(hostname));

sprintf(tempStr, "\n%sStarting FTP Server on host %s in port %d\n", ctime(&currentime), hostname, port);

if (write(fd2, tempStr, strlen(tempStr)) == -1)
    DieWithError("write(): failed");

最佳答案

您的条件已关闭。注意括号。应该是:

if ((fd2 = open(logFile, O_RDWR |O_APPEND | O_CREAT , 0666)) == -1)
//                                                        ^^^    ^^^

有时候最好不要比自己聪明:

int fd = open(...);

if (fd == -1) { DieWithError(); }

关于c - 文件描述符,open() 返回零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13169693/

相关文章:

无法以附加或写入模式打开文件

C child 读给 "resource temporarily unavailable"

c - 为什么验证密码的代码总是拒绝输入?

没有 C 标准库的 C 程序。如何?

c - 返回指向 C 中结构的指针

c++ - _get_timezone 如何工作?

C编程: how to fill an array?

c - RabbitMq C API : emulating "rabbitmqctl cluster_status -n rabbit@<remote hostname>" from C API

c++ - 通过按空格键结束键盘输入数据,而不是输入键 c/c++

c - 如何从ATmega32中的软件SPI读取32位变量?