![]() |
VOOZH | about |
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++.
The syntax of system() function is:
int system(const char *command);
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.
Hello, World! Command executed successfully.
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.
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.
Some common uses of system() in Windows OS are:
However, making a call to system command should be avoided due to the following reasons:
Let us take a simple C++ code to output Hello World using the system(“pause”):
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:
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():
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.
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,
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.