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 
#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

Leave a Comment