简体   繁体   中英

When running a program from within a program using system() in stdlib.h, how do I simulate typing to feed the sub-program's scanf call?

I am writing a program to run a different program over and over, giving it different input to a question each time, checking the output. system("the_program") accomplishes this, but how do I give that program input when it runs scanf() ?

The simplest way is to write a file, and pass it to the child using redirection ( system("the_program < the_file") ).

But, and this is much better, you can make a pipe between your program and the child. The child needs to have its standard input (file descriptor 0) connected to the reading side of the pipe. system is synchronous, so besides pipe and dup2 you need the fork and execve system calls. Luckily, there is a wrapper for this process: popen("the_program", "w") . It returns a FILE* that you can write to. Close the FILE* with pclose , and be sure to read the manual because it is different from fclose!

In the case where you are writing both parent and child programs , there is no need to a solve a problem arising by simulating something else, when we can just pass in arguments:

system('./the_program the_scanf_input')

And of course the_program:

var = argv[1] //this was var = scanf('%', &var)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM