Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect stdin to stdout

Tags:

c

stdout

stdin

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
like image 452
Mike Henderson Avatar asked Jul 23 '26 13:07

Mike Henderson


1 Answers

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.

like image 64
Nick ODell Avatar answered Jul 25 '26 06:07

Nick ODell