Ask Your Question
0

What is a portable method for determining if a command exists in C/C++?

asked 2023-06-03 20:29:44 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-06-03 20:44:01 +0000

woof gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-03 20:29:44 +0000

Seen: 13 times

Last updated: Jun 03 '23