C语言。从标准输出读取

11

我遇到了一些库函数的问题。 我需要编写一些使用库函数的C代码,该函数会在屏幕上打印它的内部步骤。 我不关心它的返回值,只关心它所打印的步骤。 因此,我认为我应该从标准输出中读取,并将读取的字符串复制到缓冲区。 我已经尝试使用fscanf和dup2,但无法从标准输出中读取。请问有人可以帮帮我吗?


1
请展示您尝试过的代码!如果您创建了一个管道并正确使用了 dup2,那么您应该已经能够完成您正在尝试的操作。 - Carl Norum
4个回答

17

以下是不使用文件并将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<<<

真是一个棒极了的答案! - étale-cohomology

8

您应该能够打开一个管道,将写端复制到stdout中,然后从管道的读端读取数据。以下是示例代码(包括错误检查):

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

好的,我用了一个非纯解决方案来修复它。我使用了C ++。 - user2479368

2
    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

0

我假设你指的是标准输入。另一个可能的函数是gets,使用man gets来了解它的工作原理(非常简单)。请展示你的代码并解释你失败的地方,以便得到更好的答案。


2
不,OP在谈论“标准输出(stdout)”。他有一个写入stdout的库函数,并且他想要拦截该输出。 - Carl Norum
好的,但是还有一件事我不明白。为什么如果我想读取已写入的文件,我不能呢?我不能发布代码,因为必须等待8个小时:S - user2479368

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接