6

我打开一个文件并想在其中写一些东西。问题是 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");
4

2 回答 2

10

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

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

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

int fd = open(...);

if (fd == -1) { DieWithError(); }
于 2012-11-01T01:23:24.087 回答
7

这是错误的。

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");
于 2012-11-01T01:23:24.233 回答