Get Linux Distribution Name using C++

Get Linux Distribution Name using C++

When working on an application that needs to run on Linux, you may need to determine the name of the Linux distribution at runtime. This information can be useful for a variety of purposes, such as adjusting the behavior of an application based on the capabilities of the underlying system. This tutorial demonstrates how to get the Linux distribution name using C++.

One way to obtain the distribution name is by reading the /etc/os-release file, which is present on most Linux distributions. The NAME field in this file typically contains the name of the Linux distribution.

Here's a part of an example /etc/os-release file on an Ubuntu distribution:

PRETTY_NAME="Ubuntu 24.04 LTS"
NAME="Ubuntu"
VERSION_ID="24.04"
VERSION="24.04 LTS (Noble Numbat)"
VERSION_CODENAME=noble
...

In the following example, the /etc/os-release file is read using an ifstream object. Regex pattern is used to search for the Linux distribution name. We use regex_match to match each line of the file against the regular expression. This function returns a boolean value that indicates whether a match was found or not. If we find a match, we extract the distribution name and assign it to the variable. Finally, we output the distribution name to the console.

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

int main()
{
    std::ifstream stream("/etc/os-release");
    std::string line;
    std::regex nameRegex("^NAME=\"(.*?)\"$");
    std::smatch match;

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

    std::cout << name << std::endl;

    return 0;
}

Output:

Ubuntu

Leave a Comment

Cancel reply

Your email address will not be published.