2012-11-01 168 views
3

我打開一個文件,並想寫入一些東西。問題是由於某些原因,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"); 
+1

什麼是'logfile'?它是'/ dev/console'嗎? –

+0

如果你在Linux上,通過'strace'運行它。 –

+0

logFile只是一個logFile.log的路徑 – Kelis

回答

7

你的條件是關閉的。注意括號。它應該是:

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

有時候它可能是最好不要智取自己:

int fd = open(...); 

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

不錯,一個精確的領帶......第二個 –

+0

謝謝老兄,看來我很累... – Kelis

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");