如何用C++检测操作系统及其版本
时间: 2023-12-22 07:02:37 浏览: 120
我们可以使用C++中的系统调用来检测操作系统及其版本。具体的方法是,我们可以使用GetVersionEx函数或GetNativeSystemInfo函数来获取操作系统的版本信息。
下面是一个示例代码:
```c++
#include <iostream>
#include <windows.h>
int main()
{
OSVERSIONINFOEX osvi;
SYSTEM_INFO si;
BOOL bOsVersionInfoEx;
ZeroMemory(&si, sizeof(SYSTEM_INFO));
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO*)&osvi);
if (bOsVersionInfoEx == FALSE)
{
std::cout << "GetVersionEx failed!" << std::endl;
return 1;
}
// 输出操作系统版本信息
std::cout << "Operating System: ";
switch (osvi.dwMajorVersion)
{
case 5:
if (osvi.dwMinorVersion == 0)
{
if (osvi.wProductType == VER_NT_WORKSTATION)
std::cout << "Windows 2000 Professional" << std::endl;
else
std::cout << "Windows 2000 Server" << std::endl;
}
else if (osvi.dwMinorVersion == 1)
{
if (osvi.wProductType == VER_NT_WORKSTATION)
std::cout << "Windows XP" << std::endl;
else
std::cout << "Windows Server 2003" << std::endl;
}
break;
case 6:
if (osvi.dwMinorVersion == 0)
{
if (osvi.wProductType == VER_NT_WORKSTATION)
std::cout << "Windows Vista" << std::endl;
else
std::cout << "Windows Server 2008" << std::endl;
}
else if (osvi.dwMinorVersion == 1)
{
if (osvi.wProductType == VER_NT_WORKSTATION)
std::cout << "Windows 7" << std::endl;
else
std::cout << "Windows Server 2008 R2" << std::endl;
}
else if (osvi.dwMinorVersion == 2)
{
if (osvi.wProductType == VER_NT_WORKSTATION)
std::cout << "Windows 8" << std::endl;
else
std::cout << "Windows Server 2012" << std::endl;
}
else if (osvi.dwMinorVersion == 3)
{
if (osvi.wProductType == VER_NT_WORKSTATION)
std::cout << "Windows 8.1" << std::endl;
else
std::cout << "Windows Server 2012 R2" << std::endl;
}
else if (osvi.dwMinorVersion == 4)
{
if (osvi.wProductType == VER_NT_WORKSTATION)
std::cout << "Windows 10" << std::endl;
else
std::cout << "Windows Server 2016" << std::endl;
}
break;
default:
std::cout << "Unknown" << std::endl;
break;
}
return 0;
}
```
此代码将输出当前操作系统的名称,例如“Windows 10”。
阅读全文