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.

[bash] #include <stdio.h> char *cuserid(char *string); [/bash]
 $ 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; } [/bash]
 $ gcc -o get_username get_username.c 
 $ ./get_username 

This users home directory is : /home/myusername

Leave a Comment