Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The portable method for determining if a command exists in C/C++ is to use the system function to execute the command with the "-v" or "--version" option and check if the return value is zero.

Here is an example code snippet:

#include <cstdlib>

int commandExists(const char* cmd) {
    char buf[1024];
    snprintf(buf, sizeof(buf), "command -v %s > /dev/null 2>&1", cmd);
    return system(buf) == 0;
}

int main() {
    const char* cmd = "ls";
    if (commandExists(cmd)) {
        // Command exists, do something...
    } else {
        // Command does not exist, handle error...
    }
    return 0;
}

In this example, the command "ls" is checked for existence by executing the "command -v ls" command and redirecting the output to /dev/null to suppress it. If the return value of system is zero, the command exists.