2013-02-22 50 views
0

我正在運行下面的代碼,我無法重定向到一個文件。該文件已製作,但沒有任何內容。如果我刪除最後的dup2(saveout,1)聲明,我可以創建並寫入文件,但我無法回到終端,這很重要。只要我把dup2(saveout,1)放回到我的代碼中,重定向就停止工作,但我可以回到終端。我不明白爲什麼會發生這種情況。我想重定向並返回到終端。在Linux中使用dup2()和create()在循環內重定向

的main.cpp

#include <cstdlib> 
#include <stdio.h> 
#include <stdlib.h> 
#include <fcntl.h> 
#include <string> 
#include <iostream> 
#include <string.h> 
#include <unistd.h> 
#include <sys/stat.h> 
using namespace std; 

void printmessage() { 
    printf("this is the message\n"); 
} 

int main(int argc, char** argv) {  
    int saveout; 
    int fd; 
    saveout = dup(1); 

    for (int i = 0; i < 10; i++) { 
     fd = creat("/home/carl/example.txt",O_CREAT|O_APPEND); 
     dup2(fd, 1); 
     close(fd); 
     printf("Testing the message"); 
     printmessage(); 

     dup2(saveout,1); 
     close(saveout); 
    } 
    return 0; 
} 

回答

0

第二個dup2(saveout,1);將失敗,因爲您關閉了saveout

0

printf is buffered by default.(行由行輸出到一個TTY,也許不同的輸出到別的東西)。雙方你撥打dup2(..., 1)之前,您應該fflush沖洗:

fflush(stdout); 
+0

謝謝你做到了。 – 2013-02-25 16:55:07

1

這是一個文件權限問題,你應該閱讀的您正在使用的功能的手冊頁。

creat() takes as first argument the filename, and as second the file creation rights, not its opening mode. 

科瑞()功能是一種簡單的open()調用,有一些特定的標誌,讓你只需要設置權限。如果你想打開你的文件,如果他不存在創建它,使用

open(filename, O_CREAT | O_RDWR | O_APPEND, 0600) for example, or 
creat(filename, 0600), 

其中大部分是同等的,但你將無法追加文本,如「科瑞

()相當於打開()標誌等於O_CREAT | O_WRONLY | O_TRUNC「