简体   繁体   English

如何将stdin回显到stdout

[英]How to echo stdin to stdout

it's a very simple question, how to echo every char that I type in stdin to stdout? 这是一个非常简单的问题,如何将我在stdin中键入的每个字符回显到stdout? I'm trying to do it for a long time and I've tried many ways and no one works well. 我尝试了很长时间,并且尝试了很多方法,但没有人能很好地完成工作。 The best I could do was to get what I typed after application end. 我能做的最好的事情就是得到应用程序结束后输入的内容。

The best I did was: 我所做的最好的事情是:

#include <stdio.h>

int main()
{
    while (1)
    {
        int ch = getc(stdin);

        if(ch == EOF) break;

        putc(ch, stdout);
    }
    return 0;
}

Thanks. 谢谢。

You need to flush the stdout : 您需要刷新stdout

int main()
{
    while (1)
    {
        int ch = getc(stdin);
        fflush(stdout);
        if(ch == EOF) break;

        putc(ch, stdout);
    }
    return 0;
}

The code you have should work just fine, as long as you hit . 只要您按 ,您拥有的代码就应该可以正常工作。 In most systems, the program will get input in a line oriented fashion. 在大多数系统中,程序将以面向行的方式获取输入。 If you want to echo the key immediately after it is hit, you will need to change the input method for the program. 如果要在击键后立即回显键,则需要更改程序的输入法。 On many systems, this would be getch() , but there may be other requirements you have to satisfy before you can use the interface ( ncurses requires some additional setup, for example). 在许多系统上,这将是getch() ,但是在使用该接口之前,您可能还需要满足其他要求(例如, ncurses需要一些其他设置)。

When echoing the data immediately after the key is hit, you will be required to flush the output in some way. 按下键后立即回显数据时,将要求您以某种方式刷新输出。 If you are sending the output to stdout , then a call to fflush() will work. 如果将输出发送到stdout ,则对fflush()的调用将起作用。 If you are using some system specific output command, you may be required to call some kind or window refresh routine. 如果您使用某些系统特定的输出命令,则可能需要调用某种或窗口刷新例程。

I wonder if a better way would be: 我想知道是否有更好的方法:

int ch;
while((ch = getchar()) >= 0)
{
    putchar(ch);
}

Then if you call this: 然后,如果您致电:

echo this is my input | 回声这是我的输入 ./myprogram ./myprogram

it would output the entire stdin this is my input without hitting the enter key. 它会输出整个标准输入, this is my input而无需按enter键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM