You need to locate the user's home directory. To do this, Use getpwent
to get the user record and from there the home directory. Then add the rest of the path to your xml file /myuserprojectdir/xmlfilename.xml
to the value you get.
This will work even if the users's home directory is not /home/$USER
. It works on linux and OSX, and will probably work on windows with cygwin installed.
Here's a working example with error checking omitted for clarity:
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
main()
{
char* user = getlogin();
struct passwd* userrecord;
while((userrecord = getpwent()) != 0)
if (0 == strcmp(user, userrecord->pw_name))
printf("save file is %s/myuserprojectdir/xmlfilename.xml\n", userrecord->pw_dir);
}
output:
save file is /Users/alex/myuserprojectdir/xmlfilename.xml
This is how it works (from man getpwent
):
struct passwd * getpwent(void);
// The getpwent() function sequentially reads the password database and is intended for programs that wish to
process the complete list of users.
struct passwd {
char *pw_name; /* user name */ // <<----- check this one
char *pw_passwd; /* encrypted password */
uid_t pw_uid; /* user uid */
gid_t pw_gid; /* user gid */
time_t pw_change; /* password change time */
char *pw_class; /* user access class */
char *pw_gecos; /* Honeywell login info */
char *pw_dir; /* home directory */ // <<----- read this one
char *pw_shell; /* default shell */
time_t pw_expire; /* account expiration */
int pw_fields; /* internal: fields filled in */
};
To get the username, use getlogin
... here's a snippet from man getlogin
.
char * getlogin(void);
// The getlogin() routine returns the login name of the user associated with the current session ...