Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting dos command output in C

Tags:

c

system

exec

dos

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?

like image 888
user1224976 Avatar asked Jan 17 '23 17:01

user1224976


2 Answers

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.

like image 117
Matteo Italia Avatar answered Jan 25 '23 00:01

Matteo Italia


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 ...//
//                                         //
like image 44
Tabrez Ahmed Avatar answered Jan 25 '23 02:01

Tabrez Ahmed