Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 352
BlueElixir Avatar asked Jan 22 '15 15:01

BlueElixir


2 Answers

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 ) );
like image 53
SGrebenkin Avatar answered Oct 09 '22 05:10

SGrebenkin


The output of a system call should show up on stdout.

I do not think those commands generally have any output to display if they are successful. Try adding a dir or pwd after to list the directory you are in.

If you want to get the output from the commands into the program for processing that is another issue. You will have to use os specific api, or maybe redirect the output into a file you can read.

like image 38
rileymat Avatar answered Oct 09 '22 04:10

rileymat