Get Ubuntu Version using C++

Get Ubuntu Version using C++

Ubuntu is a popular Linux distribution which has regular releases. With each release, it has a specific version number. Retrieving the Ubuntu version using C++ can be helpful in various scenarios. For example, you want to ensure that a C++ application is compatible with the Ubuntu version it is running on. Also, it can be useful for collecting system information for monitoring and diagnostic purposes. This tutorial shows how to get the Ubuntu version using C++.

The /etc/lsb-release file holds various details about the distribution, including the Ubuntu version, which we can be extracted using C++ and regex. Here is an example of /etc/lsb-release file:

DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=22.04
DISTRIB_CODENAME=jammy
DISTRIB_DESCRIPTION="Ubuntu 22.04.2 LTS"

In the following example, the /etc/lsb-release file is read using an ifstream object. Regex pattern is used to search for the Ubuntu version. The [0-9.]+ pattern matches one or more digits and dots, which corresponds to the Ubuntu version (e.g. 22.04.2, 20.04.6). The regex_search function is used to perform the regex search on each line of the file. This function returns a boolean value that indicates whether a match was found or not. If a match is found, the match object will be populated with the matched results, which can be retrieved using its member function str. The result is stored in the ubuntuVersion variable, which printed to the console.

#include <iostream>
#include <fstream>
#include <regex>

int main()
{
    std::ifstream stream("/etc/lsb-release");
    std::string line;
    std::regex versionRegex("^DISTRIB_DESCRIPTION=.*?([0-9.]+)");
    std::smatch match;

    std::string ubuntuVersion;
    while (std::getline(stream, line)) {
        if (std::regex_search(line, match, versionRegex)) {
            ubuntuVersion = match[1].str();
            break;
        }
    }

    std::cout << ubuntuVersion << std::endl;

    return 0;
}

The output might look like this:

22.04.2

Leave a Comment

Cancel reply

Your email address will not be published.