您需要找到用户的主目录。为此,使用getpwent 获取用户记录并从那里获取主目录。然后将您的xml文件/myuserprojectdir/xmlfilename.xml的其余路径添加到您获得的值中。
即使用户的主目录不是/home/$USER,这也会起作用。它适用于 linux 和 OSX,并且可能适用于安装了cygwin 的 Windows。
这是一个工作示例为了清楚起见省略了错误检查:
#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);
}
输出:
save file is /Users/alex/myuserprojectdir/xmlfilename.xml
这就是它的工作原理(来自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 */
};
要获取用户名,请使用getlogin...这是来自man getlogin 的sn-p。
char * getlogin(void);
// The getlogin() routine returns the login name of the user associated with the current session ...