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

后端 未结 2 1343
渐次进展
渐次进展 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:20

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

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题