C语言。从标准输出读取 [英] C language. Read from stdout

查看:397
本文介绍了C语言。从标准输出读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些麻烦与库函数。
我必须写一个使用库函数它打印屏幕内部步骤对一些C code。
我没有兴趣到它的返回值,而只是印刷步骤。
所以,我觉得我已经从标准输出读取和读字符串在缓冲区拷贝。
我已经尝试过的fscanf和dup2,但我不能从标准输出读取。请,任何人都可以帮我吗?

I have some troubles with a library function. I have to write some C code that uses a library function which prints on the screen its internal steps. I am not interested to its return value, but only to printed steps. So, I think I have to read from standard output and to copy read strings in a buffer. I already tried fscanf and dup2 but I can't read from standard output. Please, could anyone help me?

推荐答案

在previous答案的扩展版本,没有使用文件,并在管道中捕获标准输出,而不是:

An expanded version of the previous answer, without using files, and capturing stdout in a pipe, instead:

#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);
}

生成以下的输出:

Generates the following output:

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

这篇关于C语言。从标准输出读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆