views:

321

answers:

2

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

Kinda like backtics in Perl.

Not looking for a cross platform thing. I just need the quickest solution for VC++.

Any ideas?

+4  A: 

WinAPI solution:

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

Mad Fish
It's shocking to me that this is the simplest way of doing backtics in VC.. http://msdn.microsoft.com/en-us/library/ms682499(VS.85).aspxIt's hundreds of lines of code!
Assaf Lavie
A: 

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");
   }
}

Seems simple enough. Just need to wrap it with C++ goodness.

Assaf Lavie
To quote from the MSDN - "when used in a Windows program, the _popen function returns an invalid file pointer that will cause the program to hang indefinitely". It will work in console apps, if that's of any use.
anon
Well, console apps is indeed what I'm trying to execute. But your comment is important.. maybe a more robust solution is in order.
Assaf Lavie
Neil, actually, I tried the above with "notepad.exe" and it just waits until I close notepad and returns...
Assaf Lavie
That's not what it means. It means you can't use popen() inside a Windows GUI app. You can use it to execute a GUI app from a console app.
anon
DOH! guess I should have read more carefully.
Assaf Lavie