Execute a process and return its standard output in VC++

冷暖自知 提交于 2019-12-20 04:22:53

问题


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?


回答1:


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).




回答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.



来源:https://stackoverflow.com/questions/1184433/execute-a-process-and-return-its-standard-output-in-vc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!