×

C Tutorial

C Basics

C Data Types

C Input/Output

C Operators

C Conditional Statements

C Control Statements

C Strings

C Functions

C Arrays

C Structure and Unions

C Pointers

C Preprocessor Directives

C Command-line Arguments

C File Handlings

C Graphics

C Advance Topics

C Tips and Tricks

C Important Topics

C Practice

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. By IncludeHelp Last updated : April 13, 2023

Overview

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).

How to Execute System Commands in C?

To execute system commands in C, use system() function which is a library function of stdlib.h header file. It can also be 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.

Syntax

system(char *command);

Example

The following code shows the execution of ls command using system() function in C language.

char *command = "ls";
system(command);

C program to execute system (Linux and DOS) command

#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



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.