小智 12
对于POSIX系统,我发现这个工作非常好(我在这个例子中检查avconv):
if (system("which avconv > /dev/null 2>&1")) {
// Command doesn't exist...
} else {
// Command does exist, do something with it...
}
Run Code Online (Sandbox Code Playgroud)
重定向到/ dev/null只是为了避免将任何内容打印到stdout.它仅依赖于which命令的退出值.
虽然我不认为有一种完全可移植的方法来做到这一点(有些系统甚至不支持命令解释器),system()但如果在运行命令时没有错误,则返回 0。我想您可以尝试运行您的命令,然后检查系统的返回值。
要检查命令解释器是否可用,请调用system( NULL )并检查非零值。
这是一种扫描存储在PATH变量中的所有路径的方法,扫描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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4502 次 |
| 最近记录: |