简体   繁体   中英

Determine if command line program is installed C++

I am trying to find out if a command line program is installed, so that it can be used later.

So far what I have tried is:

int whichReturn = system("command -v THE_CL_PROGRAM >/dev/null && { exit 50; }|| { exit 60; }");
if (whichReturn == 12800) { //system 'apparently' returns the return value *256 (50*256 = 12800)

    //...

}

However it seems that it always returns 60 and so fails.

Is there an easier way to do this? Or can someone point out where my mistake is please?

Thanks

A complete program using which :

isthere.cpp:

#include <iostream>
#include <cstdlib>
#include <sstream>

int main(int argc, char* argv[])
{
        std::ostringstream cmd;
        cmd << "which " << argv[1] << " >/dev/null 2>&1";
        bool isInstalled = (system(cmd.str().c_str()) == 0);
        std::cout << argv[1] << " is "<< ((isInstalled)?"":"NOT ") << "installed! << std::endl;
}

Output:

$ ./isthere ls
ls is installed!
$ ./isthere grep
grep is installed!
$ ./isthere foo
foo is NOT installed!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM