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. To learn about its usage and best practices, the C++ Course offers detailed explanations and practical examples.
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;
}
OutputHello, 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;
}
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;
}
OutputCommand 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.
Similar Reads
goto Statement in C++
The goto statement in C++ is a control flow statement that provides for an unconditional jump to the same function's predefined label statement. In simple terms, the goto is a jump statement transfers the control flow of a program to a labeled statement within the scope of the same function, breakin
5 min read
goto Statement in C
The goto statement in C allows the program to jump to some part of the code, giving you more control over its execution. While it can be useful in certain situations, like error handling or exiting complex loops, it's generally not recommended because it can make the code harder to read and maintain
4 min read
Continue Statement in C
The continue statement in C is a jump statement used to skip the current iteration of a loop and continue with the next iteration. It is used inside loops (for, while, or do-while) along with the conditional statements to bypass the remaining statements in the current iteration and move on to next i
4 min read
C - if Statement
The if in C is the simplest decision-making statement. It consists of the test condition and a block of code that is executed if and only if the given condition is true. Otherwise, it is skipped from execution. Let's take a look at an example: [GFGTABS] C #include <stdio.h> int main() { int n
4 min read
C++ if Statement
The C++ if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not executed based on a certain condition. Let's take a look at an example: [GFGTABS] C++ #include <iostream> using namespace std; int
3 min read
STD::array in C++
The array is a collection of homogeneous objects and this array container is defined for constant size arrays or (static size). This container wraps around fixed-size arrays and the information of its size are not lost when declared to a pointer. In order to utilize arrays, we need to include the ar
5 min read
Tokens in C
In C programming, tokens are the smallest units in a program that have meaningful representations. Tokens are the building blocks of a C program, and they are recognized by the C compiler to form valid expressions and statements. Tokens can be classified into various categories, each with specific r
4 min read
std::search in C++
std::search is defined in the header file <algorithm> and used to find out the presence of a subsequence satisfying a condition (equality if no such predicate is defined) with respect to another sequence. It searches the sequence [first1, last1) for the first occurrence of the subsequence defi
4 min read
isdigit() in C++
The isdigit() function in C++ checks whether a given character is a digit or not. Let's take a look at an example: [GFGTABS] C++ #include <bits/stdc++.h> using namespace std; int main() { char c = '5'; if (isdigit(c)) cout << c << " is a Digit"; else cout <<
3 min read
raise() function in C++
csignal header file declared the function raise() to handle a particular signal. Signal learns some unusual behavior in a program, and calls the signal handler. It is implemented to check if the default handler will get called or it will be ignored. Syntax: int raise ( int signal_ ) Parameter: The f
3 min read