1

我试图找出是否安装了命令行程序,以便以后可以使用。

到目前为止,我尝试过的是:

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)

    //...

}

然而,它似乎总是返回 60,所以失败了。

有没有更简单的方法来做到这一点?或者有人可以指出我的错误在哪里吗?

谢谢

4

1 回答 1

2

一个完整的程序使用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;
}

输出:

$ ./isthere ls
ls is installed!
$ ./isthere grep
grep is installed!
$ ./isthere foo
foo is NOT installed!
于 2013-11-11T17:36:23.340 回答