In system-level programming, it is often necessary to retrieve the username of the user under which the current process is running. This can be useful for logging, personalization, auditing, or environment-specific behavior.
The C standard library does not include a universal function for obtaining the current username. Instead, platform-dependent interfaces are required. On Windows systems, a dedicated API is available for this purpose. On Unix-like systems such as Linux, the username can be obtained through system user database functions provided by the POSIX.
A cross-platform approach can be implemented by separating platform-specific logic behind a single function interface:
#include <stdio.h>
#include <string.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#include <pwd.h>
#endif
int get_username(char *username, const size_t size) {
#ifdef _WIN32
DWORD len = (DWORD) size;
if (!GetUserNameA(username, &len)) {
return 1;
}
#else
struct passwd *pw = getpwuid(getuid());
if (!pw) {
return 1;
}
strncpy(username, pw->pw_name, size - 1);
username[size - 1] = '\0';
#endif
return 0;
}
int main(void) {
char username[256];
if (get_username(username, sizeof(username))) {
printf("Unable to get username\n");
return 1;
}
printf("%s\n", username);
return 0;
}
This program defines a unified function that abstracts away operating system differences. On Windows, the GetUserNameA function from the Windows API is used to obtain the current username.
On Linux and other Unix-like systems, the program uses the getuid to retrieve the current user ID, followed by the getpwuid to access the corresponding password database entry. The username is then extracted from the pw_name field.
Leave a Comment
Cancel reply