是否可以从标准输出读取? [英] Is it possible to read from stdout?

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

问题描述

如果我使用 printf ("Hello!"); 有什么方法可以读取我打印到标准输出中的内容吗?

If I use printf ("Hello!"); are there any ways to read what I've printed into stdout?

我看到了 C 语言.从标准输出读取(它使用管道)但它不起作用:

I saw C language. Read from stdout (it uses pipe) but it doesn't work:

#define _XOPEN_SOURCE

#include <stdio.h>
#include <unistd.h>

#define DIM 10

int main(void)
{
    char s[DIM];
    int fds[2];

    pipe(fds);
    dup2(fds[1], fileno(stdout)); //I added fileno()

    printf("Hello world!");

    read(fds[0], s, DIM);
    printf("\n%s",s);

    return 0;
}

我也尝试过使用文件描述符,但都不起作用:

I also tried using a file descriptor but neither it doesn't work:

#define _XOPEN_SOURCE

#include <stdio.h>
#include <unistd.h>

#define DIM 10
#define MYFILE "/path/file"

int main(void)
{
    FILE *fd;
    char s[DIM];

    fd = fopen(MYFILE,"w+");
    dup2(STDOUT_FILENO, fileno(fd));

    printf("Hello world!");

    fseek(fd, 0, SEEK_SET);
    fgets(s, DIM, fd);

    printf("\n%s",s);
    return 0;
}

我该怎么办?

推荐答案

通常不会,除非标准输出已重定向到文件.写入标准输出的函数(如 printf())不会在您的进程中的任何地方记录它们的输出,并且没有办法从普通文件以外的任何地方读取您之前的输出*.例如,如果您的进程将其输出打印到终端,那么尝试从终端读取数据将返回用户输入的内容,而不是您之前输出的内容.

Generally not, unless standard output has been redirected to a file. Functions which write to standard output (like printf()) don't record their output anywhere within your process, and there's no way to read your previous output back from anything other than a normal file*. For instance, if your process is printing its output to a terminal, trying to read data from the terminal will give you back what the user is inputting, not what you previously output.

您的第二个程序几乎在运行.不过,您需要先解决一些小问题:

Your second program is almost working. There's a few small issues you'll need to fix first, though:

  1. 第一个 printf() 的输出不会被输出,因为它缺少换行符.添加换行符,或调用 fflush(stdout) 以强制输出.

  1. The output from your first printf() won't be output, as it's missing a newline. Either add a newline, or call fflush(stdout) to force it to be output anyway.

您正在尝试 printf() 您的结果,但标准输出仍指向该文件,因此您永远看不到它.覆盖标准输出后显示内容的最简单方法是使用 fprintf(stderr, ...).

You're trying to printf() your results, but standard output is still pointing to that file, so you'll never see it. The easiest way to display something after overwriting standard output will be to use fprintf(stderr, ...).

(*: 或者某些行为很像文件的东西,比如块设备或命名管道.但你可能不会使用它们.)

(*: Or certain things which behave a lot like files, like block devices or named pipes. But you're probably not working with those.)

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

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