文件描述符,open()返回零
我打开一个文件,想要写一些东西。 问题是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(¤time), 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(); }
这是错的。
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 fd2 = open(...); if (fd2 < 0) err(1, "open failed");