c++ 判断 linux 系统 是 centos debain ubantu

180it 2024-12-14 PM 82℃ 0条

c++ 判断 linux 系统 是 centos debain ubantu

你可以通过读取 /etc/os-release 文件来判断 Linux 系统是 CentOS、Debian 还是 Ubuntu。以下是一个示例代码:

#include <iostream>
#include <fstream>
#include <string>

std::string getOSName() {
    std::ifstream file("/etc/os-release");
    if (!file.is_open()) {
        throw std::runtime_error("Could not open /etc/os-release");
    }

    std::string line;
    while (std::getline(file, line)) {
        if (line.find("ID=") == 0) {
            return line.substr(3); // Remove "ID=" prefix
        }
    }

    throw std::runtime_error("ID not found in /etc/os-release");
}

int main() {
    try {
        std::string os_name = getOSName();
        if (os_name == "centos") {
            std::cout << "This is a CentOS system." << std::endl;
        } else if (os_name == "debian") {
            std::cout << "This is a Debian system." << std::endl;
        } else if (os_name == "ubuntu") {
            std::cout << "This is an Ubuntu system." << std::endl;
        } else {
            std::cout << "This is another Linux system: " << os_name << std::endl;
        }
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
    return 0;
}

编译并运行这个程序:

g++ -o check_os main.cpp
./check_os

这个程序将读取 /etc/os-release 文件,判断系统是 CentOS、Debian 还是 Ubuntu,并输出相应的信息。如果是其他 Linux 系统,也会输出其名称。

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

c++ 判断 linux 系统 是 centos debain ubantu