Using system()
or exec()
, I can get any command to execute but they display the result into the Console. I want to execute the command and extract the output and process it, and then display it. How can I achieve this on Windows/DOS Platform?
There's nothing like that in standard C, but usually, for compatibility with POSIX, compilers implement popen
(_popen
in VC++), which starts a command (as it would do with system
) and returns a FILE *
to the stream you asked for (you can ask for stdout if you want to read the output or stdin if you want to give some input to the program).
Once you have the FILE *
, you can read it with the usual fread
/fscanf
/..., like you would do on a regular file.
If you want to have both input and output redirection things start to get a bit more complicated, since Windows compilers usually do have something like POSIX pipe
, but it isn't perfectly compatible (mostly because the Windows process creation model is different).
In this case (and in any case where you need more control on the started process than the plain popen
gives you) I would simply go with the "real" way to perform IO redirection on Windows, i.e. with CreateProcess
and the appropriate options; see e.g. here.
Matteo Italia's answer is awesome. But some compilers (especially older ones) don't support popen()
.
If popen()
is not supported, here's a possible solution.
In DOS we can redirect the output to a temporary file using >
.
Ex:
C:\> ipconfig > temp.txt
I can then open temp.txt in my C-code and then reprocess its content.
My C code for this will be something like:
system("ipconfig > temp.txt");
FILE *fp;
fp = fopen("temp.txt","r");
// //
//... Code for reprocessing can go here ...//
// //
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