Home »
C programming language
Executing system commands using C program
In this tutorial, we are going to learn how to execute system commands (Linux commands or/and MS DOS commands) in C programming language? Here we are going to discuss about 'system()' function which executes system commands.
Submitted by IncludeHelp, on May 10, 2018
Sometimes, we may need to execute Linux/Windows DOS commands through our C program. (Note: the code given below is compiled and executed on Linux GCC compiler, so here we are testing Linux commands only).
In the C programming standard library, there is a function named system () which is used to execute Linux as well as DOS commands in the C program.
A command can be assigned directly to the function as an argument and command may also input from the user and then assigned to the function, function will send command to the operating system’s particular terminal like Linux terminal or DOS commands terminal to execute, and after the execution, you will get your output and program’s execution returns to the next statement written after the system() function.
system() function in C
system() is a library function, which is defined in the stdlib.h header file. It is used to execute the Linux commands/Windows DOS commands.
Syntax:
system(char *command);
Example:
char *command = "ls";
system(command);
Program to run Linux commands within C program
#include <stdio.h>
#include <stdlib.h> //to use system()
#include <string.h> //to use strcpy()
int main()
{
char *command;
//executing ls command
strcpy(command, "ls");
printf("ls command...\n");
system(command);
//executing date command
strcpy(command, "date");
printf("date command...\n");
system(command);
return 0;
}
Output
Please run this program at your machine
TOP Interview Coding Problems/Challenges