- 1 year ago
Get name and version of OS
To get the name and version of the operating system in C++, you can use system-specific functions or libraries. Here's an example of how to do it on Windows and Linux:
On Windows (Using the Windows API):
cpp#include <iostream>
#include <Windows.h>
int main() {
OSVERSIONINFO osvi;
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
if (GetVersionEx(&osvi)) {
std::cout << "Operating System Name: Windows" << std::endl;
std::cout << "Version: " << osvi.dwMajorVersion << "." << osvi.dwMinorVersion << std::endl;
} else {
std::cerr << "Failed to retrieve OS information." << std::endl;
}
return 0;
}
On Linux:
cpp#include <iostream>
#include <sys/utsname.h>
int main() {
struct utsname os_info;
if (uname(&os_info) == 0) {
std::cout << "Operating System Name: " << os_info.sysname << std::endl;
std::cout << "Version: " << os_info.release << std::endl;
} else {
std::cerr << "Failed to retrieve OS information." << std::endl;
}
return 0;
}
The code snippets above demonstrate how to get the name and version of the operating system using the Windows API (GetVersionEx
) on Windows and the uname
function on Linux. Depending on the platform, the output will be something like:
On Windows:
yamlOperating System Name: Windows
Version: 10.0
On Linux:
yamlOperating System Name: Linux
Version: 5.4.0-81-generic
Keep in mind that these examples are simplistic and may not cover all possible cases or specific version information (e.g., build number on Windows). For more advanced or cross-platform approaches, you may consider using libraries like Boost or Qt, which provide OS-specific functions and better platform abstraction.