我打开一个文件,想在里面写点东西。问题是 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(); }
关于c - 文件描述符,open() 返回零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13169693/