2017-02-23 62 views
0

當我運行這個沒有得到輸出的printf文件描述符ç

close(2); 
fd = open("newfile.txt", O_WRONLY | O_CREAT | O_TRUNC, 0600); 
fprintf(stderr, "ERROR\n"); 
close(fd); 

它把錯誤的newfile中。

然而,當我運行這個

close(1); 
fd = open("newfile.txt", O_WRONLY | O_CREAT | O_TRUNC, 0600); 
printf("OUTPUT\n"); //fprintf(stdout, "OUTPUT\n"); 
close(fd); 

什麼也沒有發生。 newfile在文件描述符1中打開,但printf不通過。

有什麼我失蹤了嗎?

回答

0

我需要調用

fflush(stdout); 

刷新緩衝區1到文件中。

1

您正在修改FILE *下的文件描述符,所以奇怪的事情會發生是非常自然的。在一般情況下,最好只避免這樣做,在所有的,或者如果你必須更改文件描述符,

  • 使用opendup2close代替closeopen要清楚你要替換的文件描述符,

  • 在使用stdio之前,請在程序的最開始處進行所有更改。

如果你仍想與文件描述符混亂,這裏是你會怎麼做:

int fd = open("newfile.txt", O_WRONLY | O_CREAT | O_TRUNC, 0600); 
if (fd == -1) { 
    err(1, "newfile.txt"); 
} 
fflush(stdout); 
int r = dup2(fd, STDOUT_FILENO); 
if (r == -1) { 
    err(1, "dup2"); 
} 
close(fd); 

printf("OUTPUT\n"); 

// If you really need to close it later... 
fflush(stdout); 
close(STDOUT_FILENO);