2013-06-12 183 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

多么真棒的答案! –