简体   繁体   English

将标准输入重定向到标准输出

[英]Redirect stdin to stdout

Let's say I have a trivial C program that adds 2 numbers together:假设我有一个简单的 C 程序,它将 2 个数字加在一起:

#include <stdio.h>

int main(void) {
    int a, b;
    printf("Enter a: "); scanf("%d", &a);
    printf("Enter b: "); scanf("%d", &b);

    printf("a + b = %d\n", a + b);
    return 0;
}

Instead of typing into the termnial every time it executes, I enter the values of a and b into a file:我没有在每次执行时都输入终端,而是将ab的值输入到文件中:

// input.txt
10
20

I then redirect stdin to this file:然后我将stdin到这个文件:

./a.out < input.txt

The program works but its output is a bit messed up:该程序有效,但它的 output 有点混乱:

Enter a: Enter b: a + b = 30

Is there a way to redirect stdin to stdout so the output appears as if a user typed the values manually, ie:有没有办法将标准输入重定向到标准输出,所以 output 看起来好像用户手动键入了值,即:

Enter a: 10
Enter b: 20
a + b = 30

You could use expect for this.您可以为此使用期望。 Expect is a tool for automating interactive command-line programs. Expect 是一个自动化交互式命令行程序的工具。 Here's how you could automate typing those values in:以下是您可以如何自动输入这些值:

#!/usr/bin/expect
set timeout 20

spawn "./a.out"

expect "Enter a: " { send "10\r" }
expect "Enter b: " { send "20\r" }

interact

This produces output like this:这会产生 output ,如下所示:

$ ./expect     
spawn ./test
Enter a: 10
Enter b: 20
a + b = 30

There are more examples here .这里有更多的例子。

Forget prompting;忘记提示; try this:尝试这个:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int a, b;
    if (scanf("%d%d", &a, &b) != 2) exit(EXIT_FAILURE);
    printf("%d + %d = %d\n", a, b, a + b);
    return 0;
}

You may want to find a way to allow your users to know what the executable is about, maybe adding command-line options?您可能想找到一种方法让您的用户知道可执行文件的内容,也许是添加命令行选项?

$ echo "10 20" |./a.out
10 + 20 = 30

$ ./a.out --help
Program reads two integers and displays their sum

$

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

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