C program to get username of Linux / Identify username of the running process

cuserid() returns a pointer to a string containing a username associated with the effective user ID of the process.

#include <stdio.h>
char *cuserid(char *string);
 $ vim get_username.c 
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

#define log_fp stdout

char *user_home_dir (void) {
	//pointer to save path
        char *buf = (char *)malloc(1024*sizeof(char));
        if(buf == NULL) {
                fprintf(log_fp, "error: allocating memory for buffer %s\n",strerror(errno));

	//allocate temporary memory for saving username
        char *temp = (char *)malloc(256*sizeof(char));
        if(temp == NULL) {
                fprintf(log_fp, "error: allocating memory for temp %s\n",strerror(errno));

	//copy string from source to destination
        strcpy(buf, "/home/");

	//append one string to another string.
        strcat(buf, temp);

	//free the allocated memory used for temporary coping username

	//return the pointer to complete homepath as we created above
        return buf;

int main(int argc, char **argv) {
	char *home_dir = NULL;

	home_dir = user_home_dir();
	printf("This users home directory is : %s\n", home_dir);

	//free the memory allocated in function

	return 0;
 $ gcc -o get_username get_username.c 
 $ ./get_username 

This users home directory is : /home/myusername

Android Android Commands Android Java Applications Application Libraries Bash / Shell Scripts Bluetooth driver Build Frameworks Commands and Packages Core Kernel C Programs Development Environment Setup Documents / Books Errors & Failures File Systems Framebuffer / Display Driver git Go Language Programs Hardware Platforms Home JAVA Programs Kernel & Device Drivers Kernel Booting and Porting Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL NDK / Middleware / HAL Network Driver OS Concepts PHP Procfs Filesystem Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply