How to get the username in C/C++ in Linux?

后端 未结 5 496
灰色年华
灰色年华 2020-12-05 10:18

How can I get the actual \"username\" without using the environment (getenv, ...) in a program?

5条回答
  •  眼角桃花
    2020-12-05 10:43

    Use char *cuserid(char *s) found in stdio.h.

    #include 
    
    #define MAX_USERID_LENGTH 32
    
    int main()
    {
      char username[MAX_USERID_LENGTH];
      cuserid(username);
      printf("%s\n", username);
      return 0;
    }
    

    See for more details:

    1. https://pubs.opengroup.org/onlinepubs/007908799/xsh/cuserid.html
    2. https://serverfault.com/questions/294121/what-is-the-maximum-username-length-on-current-gnu-linux-systems

提交回复
热议问题