您需要找到用戶的主目錄。爲此,請使用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
的片段。
char * getlogin(void);
// The getlogin() routine returns the login name of the user associated with the current session ...
看起來很酷。感謝Alex – 2010-01-21 17:40:05