繁体   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