Monday, 23 April 2018

how to run system command in c

how to run system command in c

  • Use system( ) to run the command if input and output are not important.
  • Use popen( ) if control on either input or output is needed.

System:

  • system() is used to invoke an operating system command from a C/C++ program.
  • int system(const char *command);
    • stdlib.h  is needed

  • Using system(), we can execute any command that can run on terminal if operating system allows. 
  • For example, we can call system(“dir”) on Windows and system(“ls”) to list contents of a directory.

Example Program:

#include <stdio.h>
#include <string.h>

int main () {
    char command[256];

    strcpy( command, "ls -l" );
    system(command);
   
    return 0;
}

Output:

sample$ ./a.out
total 156
-rw-rw-r-- 1 labuser labuser     159 Dec 18 21:59 '
-rw-rw-r-- 1 labuser labuser     338 Aug  3  2017 ]
-rw-rw-r-- 1 labuser labuser    1035 May 16  2017 access.c
-rwxrwxr-x 1 labuser labuser    8688 Apr 23 21:52 a.out
-rw-rw-r-- 1 labuser labuser     231 May 16  2017 array_init.c
-rw-rw-r-- 1 labuser labuser     585 May 19  2017 array_size.c
-rw-rw-r-- 1 labuser labuser     347 Aug 30  2017 assert.c
-rw-rw-r-- 1 labuser labuser     992 Jan 31 21:14 backtrace.c


No comments:

Post a Comment