2010-01-21 26 views
1

我正在開發一個可移植的C++應用程序。開發環境是Linux。我有一個從Xml文件加載數據並從中創建對象模型的代碼。當前文件路徑爲/home/myuser/projectdir/xmlfilename.xml。當我從主目錄名稱不同的另一臺計算機使用時,這是有問題的。我嘗試了類似~/myuserprojectdir/xmlfilename.xml但它沒有奏效。在便攜式C++應用程序上使用相對文件路徑

那麼有沒有一種標準的方法來定義文件名,這些文件名可以在各種平臺上工作而沒有任何問題?或者任何可以在Linux機器上運行的標準方法?

有什麼想法?

回答

2

您需要找到用戶的主目錄。爲此,請使用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 ... 
+0

看起來很酷。感謝Alex – 2010-01-21 17:40:05

0

或任何會在Linux機器上運行的標準方法是什麼?

在Linux上,採取從freedesktop.org看看XDG Base Directory Specification。它指定不同種類文件的位置,例如數據,配置等。