检查是否在 C++ 中使用 termux 或普通发行版

Check if using termux or normal distro in C++

我有一个程序可以检查是否安装了 apt、apt-get 和 dpkg。但现在我需要检查是否使用普通发行版(如 Mint、Ubuntu 等)或使用 termux 来更改路径,我该怎么做?

我已经试过了,但它说路径不存在(在普通发行版上):

std::ifstream aptget("/usr/bin/apt-get");
std::ifstream dpkg("/usr/bin/dpkg");
std::ifstream termuxapt("/data/data/com.termux/files/usr/bin/apt");
std::ifstream termuxaptget("/data/data/com.termux/files/usr/bin/apt-get");
std::ifstream termuxdpkg("/data/data/com.termux/files/usr/bin/dpkg");
if (!apt.is_open()) {
    cout << "Path not found" << endl;
} else if(!aptget.is_open()) {
    cout << "Path not found" << endl;
} else if(!dpkg.is_open()) {
    cout << "Path not found" << endl;
} else if(!termuxapt.is_open()) {
    cout << "Path not found" << endl;
} else if(!termuxaptget.is_open()) {
    cout << "Path not found" << endl;
} else if(!termuxdpkg.is_open()) {
    cout << "Path not found" << endl;
} else {
    cout << "Path found" << endl;
}

您的代码存在问题,您在打开 ifsteram 之前检查它是否已打开。 如您在本文档中所见:std::ifstream::is_open:

Returns whether the stream is currently associated to a file. Streams can be associated to files by a successful call to member open or directly on construction, and disassociated by calling close or on destruction.

因此,您可以尝试打开每个文件。但是有风险。

在 C++ 中有更好的方法来检查文件是否存在。 查看更多详细信息:使用标准 C++/C++11/C 检查文件是否存在的最快方法?