Tuesday, 15 April 2014

Execute Shell Command from within C C++ program

If you want to execute shell command from within your application.
Here is the solution.
The Shell command can be executed from within your C or C++ program in two ways
 
1. Using "system(...)" function 
   #include <iostream>

   int main( int argc, const char * argv[] )

   {      

          char command[] = "ls";

          int status = system( command );

          return 0;
   }
   
    The only disadvantage of this method is you cannot track
    or read the result of command. The output will be seen on
    terminal.

   
    The return value of system() will just represent whether
    command executed successfully or not 

    status == 0 -> Successful
    status != 0 -> Unsuccessful
 

2. Using popen(...), pclose(...)
    Problem of reading from shell can be resolved with use of
    popen and pclose.


#include <stdio.h>

FILE *popen(const char *command, const char *mode);
   
    The popen(...)  function will execute the shell command
    specified in variable command and it will create a pipe
    between the launching program and the executed
    command.

    Also will return a pointer to a stream which can be read
    from or write to the pipe.


   
   #include <iostream>

   int main( int argc, const char * argv[] )

   {      
         FILE * fp ;
         char tstCommand[] ="ls *";
         char path[PATH_MAX];
         fp = popen(tstCommand, "r");
         while ( fgets( path, PATH_MAX, fp ) != NULL )
               cout << path << endl

         pclose(fp);
         return 0;
   }


Tags:
execute shell command in c, execute shell command in c code, execute shell command in c linux,execute shell command in c mac,execute shell command in cpp, shell command in c program, shell command in c++ program, shell command in xcode,



No comments:

Post a Comment