Easy Tutorial
❮ C Function Sqrt C Function Strstr ❯

C Library Function - system()

C Standard Library - <stdlib.h>

Description

The C library function int system(const char *command) passes the command name or program name specified by command to the host environment to be executed by the command processor, and returns after the command has been completed.

Declaration

Here is the declaration for the system() function.

int system(const char *command)

Parameters

Return Value

If an error occurs, the return value is -1, otherwise it returns the status of the command.

Example

The following example demonstrates the use of the system() function to list all files and directories in the current directory on a Unix machine.

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

int main ()
{
   char command[50];

   strcpy( command, "ls -l" );
   system(command);

   return(0);
}

Let's compile and run the above program on a Unix machine, which will produce the following result:

drwxr-xr-x 2 apache apache 4096 Aug 22 07:25 hsperfdata_apache
drwxr-xr-x 2 railo railo 4096 Aug 21 18:48 hsperfdata_railo
rw------ 1 apache apache 8 Aug 21 18:48 mod_mono_dashboard_XXGLOBAL_1
rw------ 1 apache apache 8 Aug 21 18:48 mod_mono_dashboard_asp_2
srwx---- 1 apache apache 0 Aug 22 05:28 mod_mono_server_asp
rw------ 1 apache apache 0 Aug 22 05:28 mod_mono_server_asp_1280495620
srwx---- 1 apache apache 0 Aug 21 18:48 mod_mono_server_global

The following example demonstrates the use of the system() function to list all files and directories in the current directory on a Windows machine.

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

int main ()
{
   char command[50];

   strcpy( command, "dir" );
   system(command);

   return(0);
}

Let's compile and run the above program on a Windows machine, which will produce the following result:

a.txt
amit.doc
sachin
saurav
file.c

C Standard Library - <stdlib.h>

❮ C Function Sqrt C Function Strstr ❯