Search

C program in linux to find the username of a the currently logged in user

Here are three ways in which we can get the user name of the currently logged in user using a c program.

1. Using getlogin
Header file required : unistd.h
The synatx of getlogin is



The function returns a pointer to a character array containing the name of the logged in user.

The following is a program showing the usage of the getlogin



Save the file as get_login.c. Compile and execute it.

The output should be the username with which we have currently logged.

2.Using getlogin_r

Header file required : unistd.h

The syntax of getlogin_r is



The function returns the login name in the variable buf, as long as the name does not exceed size parameter passed to the function.
The following is an example showing the usage of getlogin_r



Save the file as get_login_r.c. Compile and execute it.



The function returns the login name in the variable buf, as long as the name does not exceed size parameter passed to the function.

3.Using cuserid

Header file required stdio.h

The syntax of userid is



The function returns the user name in the string which is passed as the argument.The string should have enough space to accommodate the name .

Following is an example showing the usage of the function cuserid.



Save the file as get_cuserid.c. Compile and execute it.


Follow by Email