nicfv
nicfv

Reputation: 502

Is it possible to capture standard input with tee?

Is it possible to capture input from scanf(...) when I pipe my program to the tee function? For example, I have this program:

int main() {
    int d;
    printf("Enter a number: ");
    scanf("%d", &d);
    printf("Your number is %d\n", d);
}

When I execute the command ./a.out | tee out.txt, I see

7
Enter a number: Your number is 7

And out.txt is:

Enter a number: Your number is 7

How can I get the terminal and output file to both show:

Enter a number: 7
Your number is 7

Upvotes: 2

Views: 343

Answers (1)

William Pursell
William Pursell

Reputation: 212454

If you want to capture a terminal session, use script. eg:

$ cat a.c
#include <stdio.h>
int
main(void)
{
        int d;
        printf("Enter a number: ");
        if( scanf("%d", &d) == 1 ){;
                printf("Your number is %d\n", d);
        }
        return 0;
}
$ gcc a.c
$ rm -f foo
$ SHELL=/bin/sh script foo
Script started, output file is foo
sh-3.2$ ./a.out
Enter a number: 5
Your number is 5
sh-3.2$ exit
exit

Script done, output file is foo
$ cat foo
Script started on Wed Apr  7 16:48:03 2021
sh-3.2$ ./a.out
Enter a number: 5
Your number is 5
sh-3.2$ exit
exit

Script done on Wed Apr  7 16:48:13 2021

Upvotes: 2

Related Questions