简体   繁体   中英

In C, how do I give an input to a program previously called with system()?

I currently want to make a program, called with system(), accept an input, in the case where the input is not an argument. As it may be a bit unclear, I am going to illustrate my question with a simple example.

Let's assume we have 2 programs, askname.c and call.c

askname.c

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
     char name[10];
     printf("What is your name ? ");
     fgets(name, 10, stdin);
     printf("So you are %s \n", name);
 
     return 0;
}

After this I would call askname with call.c

#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[]){
char* foo ="test";
system("./askname");
//somehow make askname receive foo to display "So you are test"
return 0;
}

Any idea of how to proceed?

You don't. You use something else. Perhaps popen

FILE *fp = popen("./askname", "w");
fprintf(fp, "%s\n", foo);

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