Piping from command prompt (console)

Hello Everyone,
I have a pretty good grasp of C++ beginning concepts and I am trying to go one step further. I have some code I am trying to write and I keep hitting a dead end when it comes to one part. I am trying to run some simple command line commands with the system() call which works perfectly but I am having trouble piping the information back out of the command prompt. As an example, if I did an ipconfig and I wanted to store the result or use some portion of the result within my program. Again I am new to everything beyond arrays and pointers or at least I haven’t had much experience beyond them. Thanks for any help ahead of time.
Use the _popen function call that returns a stream associated with one end of a pipe where the other end of the pipe is associated with the created process. Then you can read from the stream the output of the launched program and close the pipe when you're done.
Assuming windows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <windows.h>

int main() {
   const DWORD BUFFER_SIZE = 2000;
   char buffer[ BUFFER_SIZE ] ;

   HANDLE hPipeRead, hPipeWrite;
   CreatePipe( &hPipeRead, &hPipeWrite, 0, 0 );
   HANDLE hConOut = GetStdHandle( STD_OUTPUT_HANDLE );
   SetStdHandle( STD_OUTPUT_HANDLE, hPipeWrite );

   STARTUPINFO         startInfo = { sizeof(STARTUPINFO) };
   PROCESS_INFORMATION procInfo;
   CreateProcess( "c:/windows/system32/ipconfig.exe", "",
                  0, 0, false, 0, 0, 0,
                  &startInfo, &procInfo );

   SetStdHandle( STD_OUTPUT_HANDLE, hConOut );

   DWORD nRead = 0;
   ReadFile( hPipeRead, buffer, BUFFER_SIZE - 1, &nRead, 0 );
   buffer[ nRead ] = 0;
   std::cout << "\n=====\n" << buffer << "\n=====\n";
}

Topic archived. No new replies allowed.