I have a binary of a program that waits for an input using scanf. I need to write a C code that will be able to simulate keyboard input. i.e. close the stdin pointer for that binary and instead repoint it to a file. I used this code
int main()
{
FILE *fin;
int result;
char string[80];
close(0);
fin = fopen("text", "r");
if(NULL == fin)
{
printf("Unable to open file.");
return 0;
}
dup(fin);
return 0;
}
But i found that each program has its own stdin pointer. Is there a way for me to simulate keyboard input for one binary from another C program ?
It's not a program you're looking for, it's capabilities of your shell:
program < input.txt
This way you push input.txt as stdin to program.
If you want a program, then you can just run a program and reroute it's output to the other programs input.
You can use a simple pipe when calling the programs as a basic measure.
Another way would be to make your keyboard simulator act as a launcher. It should start the program you are testing with stdin as your simulator's stdout.
You can do the latter by forking your program and use the parent process to create a pipe and the child process to reopen stdin (even stdout) using a file descriptor to that pipe and exec the program you want to supply the input to.
See this for pipes and this for file descriptors (as creating a pipe will give you only a file descriptor).
P.S.: Sorry about not being able to provide code at the moment, but I'm not anywhere near a UNIX workstation and a bit too rusty on UNIX OS programming to write reliable code from memory.
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