Pages

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.


2 comments:

  1. I know this is old, but for anyone else that uses this page, the following code snippet creates a memory leak:
    char *buf;
    buf=(char *)malloc(10*sizeof(char));
    buf=getlogin();

    The second line should be omitted. You don't need to allocate memory because getlogin() returns a pointer, so you lose the reference to the allocated memory.

    Simply use:
    char *buf = getlogin();
    or:
    char *buf;
    buf=getlogin();

    ReplyDelete
    Replies
    1. Thanks for pointing that out, will correct it.

      Delete