jeudi 24 février 2011

Get the username and home directory in a C program

Don't use getlogin or cuserid functions.
Don't try to guess the home directory from the username (/home/username is not working all the time).

Use getpwuid instead:

#include <sys/types.h>
#include <pwd.h>
[...]
char* username = getpwuid(getuid())->pw_name;
char* homedir = getpwuid(getuid())->pw_dir;

This works all the time, in particular if the process is not controlled by a terminal.

Aucun commentaire:

Enregistrer un commentaire