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

时间:2012-11-01 01:15:23

标签: 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");

2 个答案:

答案 0 :(得分:9)

你的条件是关闭的。记住括号。它应该是:

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

有时最好不要超越自己:

int fd = open(...);

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

答案 1 :(得分:6)

这是错误的。

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

你想要这个。

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

很难看到,因为线条很长,但括号位于错误的位置。简而言之,

if ((   fd2 = open(...) == -1     )) // your code
if ((   fd2 = (open(...) == -1)   )) // equivalent code
if ((   (fd2 = open(...)) == -1)  )) // correct code

如果该行太长,最好将其排除在if ...

之外
#include <err.h>

fd2 = open(...);
if (fd2 < 0)
    err(1, "open failed");
相关问题