Search code examples
c++windowscommand-linecmdsystem

viewing output of system() call in C++


How can I view the output of a system command. Ex:

int _tmain(int argc, _TCHAR* argv[]) {

   system("set PATH=%PATH%;C:/Program Files (x86)/myFolder/bin");
   system("cd C:/thisfolder/");

   std::cin.get();
   return 0;

}

when I run the program in Visual Studio it give me a black screen and I cannot see the command being run. I need it so I can view whether it worked or not. Thanks!


Solution

  • Use popen instead of system. See example here https://msdn.microsoft.com/en-us/library/96ayss4b.aspx

    char   psBuffer[128];
    FILE   *pPipe;
    
    if( (pPipe = _popen( "set PATH=%PATH%;C:/Program Files (x86)/myFolder/bin", "rt" )) == NULL )
        exit( 1 );
    

    then

    while(fgets(psBuffer, 128, pPipe)) {
        printf(psBuffer);
    }
    
    if (feof( pPipe))
        printf( "\nProcess returned %d\n", _pclose( pPipe ) );