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

后端 未结 2 1344
渐次进展
渐次进展 2021-01-25 05:37

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 fo

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-25 06:40

    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.

提交回复
热议问题