Run the process and return your standard output to VC ++

What is the easiest way to execute a process, wait for it to complete, and then return its standard output as a string?

Looks like backtics in Perl.

Despite the cross-platform thing. I just need the fastest solution for VC ++.

Any ideas?

+1
source share
2 answers

WinAPI Solution:

You need to create a process (see CreateProcess) with redirected input (hStdInput field in the STARTUPINFO structure) and output (hStdOutput) to your pipes (see CreatePipe), and then simply read from the channel (see ReadFile).

+4
source

hmm .. MSDN has this as an example:

int main( void )
{

   char   psBuffer[128];
   FILE   *pPipe;

        /* Run DIR so that it writes its output to a pipe. Open this
         * pipe with read text attribute so that we can read it 
         * like a text file. 
         */

   if( (pPipe = _popen( "dir *.c /on /p", "rt" )) == NULL )
      exit( 1 );

   /* Read pipe until end of file, or an error occurs. */

   while(fgets(psBuffer, 128, pPipe))
   {
      printf(psBuffer);
   }


   /* Close pipe and print return value of pPipe. */
   if (feof( pPipe))
   {
     printf( "\nProcess returned %d\n", _pclose( pPipe ) );
   }
   else
   {
     printf( "Error: Failed to read the pipe to the end.\n");
   }
}

, . ++.

+2

All Articles