Search code examples
linuxconsolehttp-redirectblack-box-testing

Possible to redirect file to a console program as if the user typed the content?


I have a C program which uses a scanf to read a number and then prints the number. I want somehow to simulate the keystrokes by redirecting a file so I can make a bash script that is supposed to do black-box-testing.

This is my program(prog):

int main(){
    int a;

    printf("Write a number: ", a);
    fflush(stdout);

    scanf("%d", &a);
    printf("\nYou entered: %d\n", a);

    return 0;
}

I then have a file(infile) with this content:

12\n

Is it possible somehow to redirect the file as input to the program to simulate user input?

When typing

./prog < infile

I get

Write a number: 
You entered: 0

Solution

  • Your file content must be this:

    12
    

    Without \n

    I tried your program and it works!

    echo '12' | ./prog