C program to get current username of Linux application

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 
[bash]
#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));
                exit(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));
                free(buf);
                exit(errno);
        }

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

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

	//free the allocated memory used for temporary coping username
        free(temp);

	//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
	free(home_dir);

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

This users home directory is : /home/myusername

Creating SSH Public and Private Key... x
Creating SSH Public and Private Key in Linux / Ubuntu

Leave a Comment

Sign up to our newsletter!

ADB Commands Android Android Applications Android Build system Application Libraries Application Stack / User Interface Bash / Shell Scripts Bluetooth driver Cloud Technologies Commands and Packages Compilation Content Management System Core Kernel C Programs Development, Debugging and Performance Tools Development and Build Development Environment Setup Django & REST Api Errors & Failures Git Hardware Platforms HTML JAVA Programs Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Multimedia NDK / Middleware / HAL Operating System Concepts PHP Programming Languages Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Source Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Web Design and Development Website Hosting Wordpress Yocto Embedded Linux