Let's say I have a trivial C program that adds 2 numbers together:
#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:
// input.txt
10
20
I then redirect stdin to this file:
./a.out < input.txt
The program works but its output is a bit messed up:
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:
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. 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:
$ ./expect
spawn ./test
Enter a: 10
Enter b: 20
a + b = 30
There are more examples here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With