List files and sub-directories

This code example demonstrates how to execute a shell command using the std::system function and handle its return code to determine the success or failure of the command execution. This example uses the command ls -la /Users to list detailed information about files and directories in the /Users directory on Unix-like systems.

Code Example

#include <iostream>
#include <cstdlib> // For EXIT_SUCCESS and system function

int main() {
    const char *shellCommand = "ls -la /Users";

    // Execute the shell command and capture its return code
    int errorCode = std::system(shellCommand);

    // Check the return code from std::system
    if (errorCode == -1) {
        // std::system returns -1 on failure to start the shell
        std::cerr << "Error initializing the shell." << std::endl;
        return EXIT_FAILURE;  // Return failure code
    } else if (errorCode != 0) {
        // std::system returns non-zero on command execution error
        std::cerr << "Command returned error code " << errorCode << std::endl;
        return EXIT_FAILURE;  // Return failure code
    } else {
        // std::system returns 0 on successful command execution
        std::cout << "Command executed successfully." << std::endl;
    }

    return EXIT_SUCCESS;  // Return success code
}

Code Explanation

Main function:
  • const char *shellCommand = "ls -la /Users";: Defines a constant character pointer shellCommand that holds the shell command to be executed (ls -la /Users lists detailed information about files in /Users).
Executing the shell command:
  • int errorCode = std::system(shellCommand);: Calls std::system with shellCommand to execute the command in the shell. The return value errorCode captures the exit status of the executed command.
Handling return codes:
  • if (errorCode == -1) { ... } else if (errorCode != 0) { ... } else { ... }:
    • if (errorCode == -1): Checks if std::system failed to execute the shell (e.g., due to a lack of available system resources).
      • Outputs an error message to std::cerr (standard error stream).
      • Returns EXIT_FAILURE to indicate failure.
    • else if (errorCode != 0): Checks if the shell command returned a non-zero exit status.
      • Outputs the specific error code returned by the command.
      • Returns EXIT_FAILURE to indicate failure.
    • else: Executes if the command ran successfully (returned 0).
      • Outputs a success message to std::cout (standard output stream).
Returning status codes:
  • return EXIT_SUCCESS; and return EXIT_FAILURE;: Indicates the overall success or failure of the program based on the command execution result.