Get Group ID (GID) on Linux using C++

Get Group ID (GID) on Linux using C++

In the Linux system, every group is distinguished by a unique identifier referred to as the group ID or GID. This identifier is crucial for determining the system resources accessible to users within that group. This tutorial demonstrates how to get group ID (GID) on Linux using C++.

Current user

The provided code snippet allows retrieving the GID of the current user in a Linux environment by using the getgid function:

#include <iostream>
#include <unistd.h>

int main()
{
    unsigned int gid = getgid();

    std::cout << gid << std::endl;

    return 0;
}

Other user

Below is a code snippet that can be employed to obtain the GID of a specified user (e.g., www-data) within a Linux environment. The getpwnam function is employed to fetch the user account information using the username. Subsequently, the GID can be extracted from the returned passwd structure.

#include <iostream>
#include <pwd.h>

int main()
{
    const char *username = "www-data";
    passwd *pwd = getpwnam(username);
    unsigned int gid = pwd->pw_gid;

    std::cout << gid << std::endl;

    return 0;
}

Leave a Comment

Cancel reply

Your email address will not be published.