Open In App

system() in C/C++

Improve
Improve
Like Article
Like
Save
Share
Report

The system() function is used to invoke an operating system command from a C/C++ program. For example, we can call system(“dir”) on Windows and system(“ls”) in a Unix-like environment to list the contents of a directory.

It is a standard library function defined in <stdlib.h> header in C and <cstdlib> in C++.

Syntax

The syntax of system() function is:

int system(const char *command);

Parameters

  • command: A pointer to a null-terminated string that contains the command we want to execute.

Return Value

  • It returns 0 if the command is successfully executed.
  • It returns a non-zero value if command execution is not completed.

Example: Program to Illustrate the system() Function

In this program, we will use the echo command to print the “Hello World” string.

C++




// C++ Program to illustrate the system function
#include <cstdlib>
#include <iostream>
using namespace std;
 
int main()
{
    // giving system command and storing return value
    int returnCode = system("echo Hello, World!");
 
    // checking if the command was executed successfully
    if (returnCode == 0) {
        cout << "Command executed successfully." << endl;
    }
    else {
        cout << "Command execution failed or returned "
                "non-zero: "
             << returnCode << endl;
    }
 
    return 0;
}


C




// C Program to illustrate the system function
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
  // giving system command and storing return value
    int returnCode = system("echo Hello, World!");
 
  // checking if the command was executed successfully
    if (returnCode == 0) {
        printf("Command executed successfully.");
    }
    else {
        printf("Command execution failed or returned "
               "non-zero: %d", returnCode);
    }
 
    return 0;
}


Output

Hello, World!
Command executed successfully.

Writing a C/C++ program that compiles and runs other programs?

We can invoke gcc from our program using system(). See below the code written for Linux. We can easily change code to run on Windows.

C++




// A C++ program that compiles and runs another C++
// program
#include <bits/stdc++.h>
using namespace std;
int main()
{
    char filename[100];
    cout << "Enter file name to compile ";
    cin.getline(filename, 100);
 
    // Build command to execute. For example if the input
    // file name is a.cpp, then str holds "gcc -o a.out
    // a.cpp" Here -o is used to specify executable file
    // name
    string str = "gcc ";
    str = str + " -o a.out " + filename;
 
    // Convert string to const char * as system requires
    // parameter of type const char *
    const char* command = str.c_str();
 
    cout << "Compiling file using " << command << endl;
    system(command);
 
    cout << "\nRunning file ";
    system("./a.out");
 
    return 0;
}


To convert the above code for Windows we need to make some changes. The executable file extension is .exe on Windows. So, when we run the compiled program, we use a.exe instead of ./a.out.

system() Function vs Using Library Functions

Some common uses of system() in Windows OS are:

  • system(“pause”): This command is used to execute the pause command and make the screen/terminal wait for a key press.
  • system(“cls”): This command is used to make the screen/terminal clear.

However, making a call to system command should be avoided due to the following reasons:

  • It’s a very expensive and resource-heavy function call.
  • Using system() makes the program non-portable to some extent which means this works only on systems that have the pause command at the system level, like DOS or Windows. But not Linux, MAC OSX, and most others.

Let us take a simple C++ code to output Hello World using the system(“pause”)

C++




// A C++ program that pauses screen at the end in Windows OS
#include <iostream>
using namespace std;
int main()
{
    cout << "Hello World!" << endl;
    system("pause");
    return 0;
}


C




// C program that pauses screen at the end in Windows OS
#include <stdio.h>
using namespace std;
 
int main()
{
    printf("Hello World!");
    system("pause");
 
    return 0;
}


The output of the above program in Windows OS:

Hello World!
Press any key to continue…

This program is OS-dependent and uses the following heavy steps:

  • It prints “Hello World!” on the screen.
  • It displays a message “Press any key to continue…”.
  • The system() function opens the shell of the Operating System that will first scan the string passed inside the system() function and then execute the command.
  • The “pause” command waits for the user input and the shell window remains open until the user presses any key.
  • When the user presses any key, the “pause command” receives an input, and the shell window is closed.

Instead of using the system(“pause”), we can also use the functions that are defined natively in C. Let us take a simple example to output Hello World with cin.get():

C++




// Replacing system() with library function
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
    cout << "Hello World!" << endl;
    cin.get(); // or getchar()
    return 0;
}


C




// Replacing system() with library function
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    printf("Hello World!");
    getchar();
 
    return 0;
}


Output

Hello World!

Thus, we see that both system(“pause”) and cin.get() are actually performing a wait for a key to be pressed, but, cin.get() is not OS dependent and neither does it follow the above-mentioned steps to pause the program.

What is the common way to check if we can run commands using system() in an OS?

The common way to check if we can run commands using system() in an OS is to check if a command processor (shell) exists in the operating system.

Using the following way, we can check if a command processor exists in an OS:

If we pass a null pointer in place of a string for the command parameter,

  • The system returns a nonzero value if a command processor exists (or the system can run).
  • Otherwise returns 0.

C++




// C++ program to check if we can run commands using
// system()
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
    if (system(NULL))
        cout << "Command processor exists";
    else
        cout << "Command processor doesn't exists";
 
    return 0;
}


C




// C program to check if we can run commands using
// system()
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    if (system(NULL))
        printf("Command processor exists");
    else
        printf("Command processor doesn't exists");
 
    return 0;
}


Output

Command processor exists

Note: The above programs may not work on online compiler as System command is disabled in most of the online compilers including GeeksforGeeks IDE.



Last Updated : 12 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads