2013-06-12 181 views
3

我有一些庫函數的麻煩。 我必須編寫一些C代碼,它使用庫函數在屏幕上打印其內部步驟。 我對它的返回值不感興趣,但只對打印的步驟感興趣。 所以,我認爲我必須從標準輸出讀取並將讀取的字符串複製到緩衝區中。 我已經嘗試過fscanf和dup2但是我無法從標準輸出中讀取。請幫幫我嗎?C語言。從標準輸出讀取

+1

顯示你試過的代碼,請!如果你製作了一個管道並正確使用了'dup2',你應該可以做你想做的事情。 –

回答

0

我假設你的意思是標準輸入。另一個可能的功能是gets,使用man gets來了解它是如何工作的(非常簡單)。請出示您的代碼並解釋您失敗的位置以獲得更好的答案。

+1

不,OP正在討論'stdout'。他有一個庫函數寫入'stdout',並且他想攔截那個輸出。 –

+0

感謝大家。我使用了發佈的解決方案。有用! ;) – user2479368

+0

好的,但仍然有一件事我不忍受。 爲什麼如果我想讀取書面文件,我不能? 我無法發佈代碼因爲8小時必須通過:S – user2479368

2

您應該能夠打開一個管道,DUP寫入結束到標準輸出,然後從管道的讀端讀,像下面,錯誤檢查:

int fds[2]; 
pipe(fds); 
dup2(fds[1], stdout); 
read(fds[0], buf, buf_sz); 
+0

好的,我用非純粹的解決方案修復了它。我用C++。 – user2479368

1
FILE *fp; 
    int stdout_bk;//is fd for stdout backup 

    stdout_bk = dup(fileno(stdout)); 
    fp=fopen("temp.txt","w");//file out, after read from file 
    dup2(fileno(fp), fileno(stdout)); 
    /* ... */ 
    fflush(stdout);//flushall(); 
    fclose(fp); 

    dup2(stdout_bk, fileno(stdout));//restore 
4

以前的答案的擴展版本,沒有使用文件,並捕獲標準輸出的管道,而不是:

#include <stdio.h> 
#include <unistd.h> 

main() 
{ 
    int stdout_bk; //is fd for stdout backup 

    printf("this is before redirection\n"); 
    stdout_bk = dup(fileno(stdout)); 

    int pipefd[2]; 
    pipe2(pipefd, 0); // O_NONBLOCK); 

    // What used to be stdout will now go to the pipe. 
    dup2(pipefd[1], fileno(stdout)); 

    printf("this is printed much later!\n"); 
    fflush(stdout);//flushall(); 
    write(pipefd[1], "good-bye", 9); // null-terminated string! 
    close(pipefd[1]); 

    dup2(stdout_bk, fileno(stdout));//restore 
    printf("this is now\n"); 

    char buf[101]; 
    read(pipefd[0], buf, 100); 
    printf("got this from the pipe >>>%s<<<\n", buf); 
} 

生成以下的輸出:

this is before redirection 
this is now 
got this from the pipe >>>this is printed much later! 
good-bye<<< 
+0

多麼真棒的答案! –