Extract dos command output in C

Using system() or exec() , I can get any command to execute, but they display the result in the Console. I want to execute a command, extract it and process it, and then display it. How can I achieve this on a Windows / DOS platform?

+4
source share
3 answers

There is nothing similar in the C standard, but as a rule, for compatibility with POSIX, compilers implement popen ( _popen in VC ++), which launches a command (as it would be when using system ) and returns FILE * to the stream you requested ( you can ask stdout if you want to read the output or stdin if you want to give some input to the program).

Once you have FILE * , you can read it with the usual fread / fscanf / ..., as if you were doing it in a regular file.

If you want to have both input redirection and output redirection, everything becomes a little more complicated, since Windows compilers usually have something like a POSIX pipe , but are not completely compatible (mainly because the model for creating Windows processes is different).

In this case (and in any case, when you need more control over the running process than a simple popen gives), I will simply move on to the "real" way of redirecting IO to Windows, that is, using CreateProcess and the corresponding parameters; see for example here .

+6
source

Matteo Italia's answer is awesome. But some compilers (especially old ones) do not support popen() .

If popen() not supported, this is a possible solution.

In DOS, we can redirect the output to a temporary file using > .

Example:

 C:\> ipconfig > temp.txt 

Then I can open temp.txt in my C code and then recycle its contents.

My C code for this would look something like this:

 system("ipconfig > temp.txt"); FILE *fp; fp = fopen("temp.txt","r"); // // //... Code for reprocessing can go here ...// // // 
+1
source

Here's an alternative answer for those who don't have popen, which should work on most systems. This code is not thread safe. I expect this to be no significant limitation in most situations.

 #include <stdio.h> #include <process.h> #include <io.h> #include <sys\stat.h> #include <assert.h> int main() { int so = dup(1); close(1); int i = creat("output.txt", S_IWRITE); assert(i == 1); // i should be 1... system("dir"); close(i); dup2(so, 1); close(so); } 
+1
source

Source: https://habr.com/ru/post/1411351/


All Articles