1

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?

Assaf Lavie
  • 73,079
  • 34
  • 148
  • 203

2 Answers2

4

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
  • 703
  • 1
  • 8
  • 12
  • 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).aspx It's hundreds of lines of code! – Assaf Lavie Jul 26 '09 at 12:49
2

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
  • 73,079
  • 34
  • 148
  • 203
  • 4
    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. –  Jul 26 '09 at 12:35
  • 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 Jul 26 '09 at 12:44
  • Neil, actually, I tried the above with "notepad.exe" and it just waits until I close notepad and returns... – Assaf Lavie Jul 26 '09 at 12:46
  • 1
    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. –  Jul 26 '09 at 13:18