如何用C++检测操作系统及其版本
时间: 2023-12-22 09:02:27 浏览: 24
可以使用以下代码来检测操作系统及其版本:
```cpp
#include <iostream>
#include <string>
#include <cstdlib>
#ifdef _WIN32
const std::string OS = "Windows";
#elif __APPLE__
const std::string OS = "MacOS";
#elif __linux__
const std::string OS = "Linux";
#else
const std::string OS = "Unknown";
#endif
int main() {
std::cout << "Current OS: " << OS << std::endl;
#ifdef _WIN32
// Windows specific code
OSVERSIONINFO info;
ZeroMemory(&info, sizeof(OSVERSIONINFO));
info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
if (GetVersionEx(&info)) {
std::cout << "Windows Version: " << info.dwMajorVersion << "." << info.dwMinorVersion << std::endl;
}
#elif __APPLE__
// MacOS specific code
std::system("sw_vers");
#elif __linux__
// Linux specific code
std::system("cat /etc/*release");
#endif
return 0;
}
```
该代码使用预编译指令来区分操作系统。然后使用操作系统特定的代码来检测版本。在Windows下,可以使用WinAPI的GetVersionEx函数来获取版本信息。在MacOS下,可以使用系统命令sw_vers来获取版本信息。在Linux下,可以使用cat /etc/*release命令来获取版本信息。