How to get the user name of the Operating system from a c program.
eg:-
-rw-r----- 1 gkuser srth1 292 Jul 27 19:28 u1.txt
i need to get gkuser as the result?
How to get the user name of the Operating system from a c program.
eg:-
-rw-r----- 1 gkuser srth1 292 Jul 27 19:28 u1.txt
i need to get gkuser as the result?
on shell type: man 2 stat
I guess you need a good book on unix system programming ...
man getuid, if you want to get the user identity of a process.
Most systems define the environment variable USER at login, so you can use that.
Won't for for programs that call setuid.
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *p=getenv("USER");
if(p==NULL) return EXIT_FAILURE;
printf("%s\n",p);
return 0;
}
or go the route of whoami ---
/* whoami.c */
#define _PROGRAM_NAME "whoami"
#include <stdlib.h>
#include <pwd.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
register struct passwd *pw;
register uid_t uid;
int c;
uid = geteuid ();
pw = getpwuid (uid);
if (pw)
{
puts (pw->pw_name);
exit (EXIT_SUCCESS);
}
fprintf (stderr,"%s: cannot find username for UID %u\n",
_PROGRAM_NAME, (unsigned) uid);
exit (EXIT_FAILURE);
}