簡體   English   中英

C語言。 從stdout讀取

[英]C language. Read from stdout

我有一些庫函數的麻煩。 我必須編寫一些使用庫函數的C代碼,它在屏幕上打印其內部步驟。 我對它的返回值不感興趣,但僅對打印步驟感興趣。 所以,我想我必須從標准輸出讀取並在緩沖區中復制讀取字符串。 我已經嘗試過fscanf和dup2但我無法從標准輸出中讀取。 拜托,有人可以幫幫我嗎?

上一個答案的擴展版本,不使用文件,並在管道中捕獲stdout,而是:

#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<<<

您應該能夠打開一個管道,將寫入端復制到stdout,然后從管道的讀取端讀取,如下所示,並進行錯誤檢查:

int fds[2];
pipe(fds);
dup2(fds[1], stdout);
read(fds[0], buf, buf_sz);
    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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM