How do I call an external program in C, such that I can write to its stdin
and read from its stdout
? There are a lot of questions like this one but none seem to fully answer it. Say for example, that I have some program in which I want some other program to do something, like this pseudocode:
int * myinput = "this is my input"
FILE ** io = external_program("otherprogram arg1 arg2");
char c;
fprintf(io[0],myinput); // Writes my input to the programs stdin
while((c = fgetc(io[1])) != EOF) {
printf("I just read %c from otherprogram!",c);
}
As I can't find it I'd assume something like external_program
may not exist. How could I get something like it though, where I have a program running externally with filedescriptors for its stdin
, stdout
, if possible also stderr
?
This way I could, for example, have some program that reads code in some language, compile it to C or some other language, and use GCC to get the result, without having to create (and possibly overwrite) files, like so:
FILE ** io = external_program("gcc -xc -");
FILE * output = open(output_file_path); // Program's own output
// ... generate C code, writing to io[0] ...
// Now write the output to our own output file
while((c = fgetc(io[1])) != EOF) {
fputs(output,c);
}
close (output);