A portable way to find out if a command exists (C / C ++)

Standard library

C provides system and popen functions to run the command. But is there a portable way to determine if a command exists?

+4
source share
4 answers

For POSIX systems, I found that this works very well (I check avconv in this example):

 if (system("which avconv > /dev/null 2>&1")) { // Command doesn't exist... } else { // Command does exist, do something with it... } 

Redirecting to / dev / null is just to avoid typing on stdout. It relies on the value of exiting one team.

+6
source

No, there is no standard C function for this.

The only solution for Unix is ​​to split getenv("PATH") into : (colon) and try to find the executable command (using the stat function) in directories.

+5
source

Although I don’t think there is a fully portable way to do this (some systems do not even support command interpreters), system() returns 0 if there were no errors when executing your command. I suppose you could just try running your command and then checking the return value of the system.

To check if the shell is available, call system( NULL ) and check for a non-zero value.

+4
source

Here is a way to scan all the paths stored in the PATH variable to scan the mathsat :

 #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <string> #include <iostream> using namespace std; int main () { struct stat sb; string delimiter = ":"; string path = string(getenv("PATH")); size_t start_pos = 0, end_pos = 0; while ((end_pos = path.find(':', start_pos)) != string::npos) { string current_path = path.substr(start_pos, end_pos - start_pos) + "/mathsat"; if ((stat(mathsat_path.c_str(), &sb) == 0) && (sb.st_mode & S_IXOTH)) { cout << "Okay" << endl; return EXIT_SUCCESS; } start_pos = end_pos + 1; } return EXIT_SUCCESS; } 
+3
source

All Articles