How to get the current OS name and version in C++

3 Answers

0 votes
#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream file("/proc/version");
    std::string osVersion;

    if (file.is_open()) {
        std::getline(file, osVersion);
        std::cout << "Operating System: " << osVersion << "\n";
    } else {
        std::cout << "Unable to open /proc/version file.\n";
    }

    return 0;
}



/*
run:

Operating System: Linux version 6.6.72+ (builder@92247b5e083e) (Chromium OS 17.0_pre498229-r33 clang version 17.0.0 (/var/cache/chromeos-cache/distfiles/egit-src/external/github.com/llvm/llvm-project 14f0776550b5a49e1c42f49a00213f7f3fa047bf), LLD 17.0.0) #1 SMP PREEMPT_DYNAMIC Sat Feb  8 10:02:01 UTC 2025

*/

 



answered Mar 27, 2025 by avibootz
0 votes
#include <sys/utsname.h>
#include <iostream>

int main() {
    struct utsname buffer;

    if (uname(&buffer) == 0) {
        std::cout << "Operating System: " << buffer.sysname << "\n";
        std::cout << "Version: " << buffer.version << "\n";
        std::cout << "Release: " << buffer.release << "\n";
    } else {
        std::cout << "Unable to retrieve OS information.\n";
    }

    return 0;
}




/*
run:

Operating System: Linux
Version: #1 SMP PREEMPT_DYNAMIC Sat Feb  8 10:02:01 UTC 2025
Release: 6.6.72+

*/

 



answered Mar 27, 2025 by avibootz
0 votes
#include <iostream>
#include <windows.h>

typedef NTSTATUS(WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);

int main() {
    RTL_OSVERSIONINFOW osVersion = { 0 };
    osVersion.dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOW);

    HMODULE ntdllHandle = GetModuleHandleW(L"ntdll.dll");
    if (ntdllHandle) {
        RtlGetVersionPtr rtlGetVersion = (RtlGetVersionPtr)GetProcAddress(ntdllHandle, "RtlGetVersion");
        if (rtlGetVersion) {
            NTSTATUS status = rtlGetVersion(&osVersion);
            if (status == 0) {
                std::cout << "Operating System: Windows " << osVersion.dwMajorVersion << "." << osVersion.dwMinorVersion << "\n";
                std::cout << "Build Number: " << osVersion.dwBuildNumber << "\n";
            }
            else {
                std::cerr << "RtlGetVersion failed with status: " << status << std::endl;
            }
        }
        else {
            std::cerr << "Failed to get RtlGetVersion address." << std::endl;
        }
    }
    else {
        std::cerr << "Failed to get ntdll.dll handle." << std::endl;
    }

    return 0;
}



/*
run:

Operating System: Windows 10.0
Build Number: 19045

*/

 



answered Mar 27, 2025 by avibootz

Related questions

3 answers 112 views
1 answer 97 views
1 answer 102 views
1 answer 105 views
1 answer 106 views
1 answer 112 views
1 answer 75 views
...