system() function in C++

In this guide, you will learn what is system() function is in C++ programming and how to use it with an example.

1. system() Function Overview

The system() function is used to execute a command or a shell command in a sub-process. It is a part of the C standard library <cstdlib> in C++. The specific behavior and supported commands depend on the underlying operating system.

Signature:

int system(const char* command);

Parameters:

- command: A string containing the command to be executed.

2. Source Code Example

#include <iostream>
#include <cstdlib>

int main() {
    std::cout << "Listing directory contents:" << std::endl;

    // Execute system command to list directory contents
    // Note: The command might vary based on the operating system
    system("ls");

    return 0;
}

Output:

Listing directory contents:
[Output of the "ls" command, listing the files and directories in the current directory]

3. Explanation

1. The program starts by printing "Listing directory contents:" to the console.

2. The system("ls") function is then called. This function executes the "ls" command, which is a common command in Unix-like operating systems to list the contents of a directory. If you are using a different OS like Windows, you might use the system("dir") command instead.

3. The output of the "ls" command is displayed, showing the files and directories in the current directory.

Note: Using the system() function should be done with caution. Executing arbitrary commands or passing unverified user input to the function can lead to security vulnerabilities and unexpected behaviors. Always ensure the command being executed is safe and does not expose sensitive system resources.


Comments