我正在尝试编译库尼汉 http://sourceforge.net/projects/libunihan/使用 MinGW 编写代码,但遇到了需要移植的功能。该函数的目的是获得规范的路径表示。它用pwd.h
(这是 POSIX,而 MinGW 不是),因此它可以通过检索 '~' 来解释主目录的使用passwd
结构体,其中包含pw_dir
。我确实找到了一些信息here http://www.suacommunity.com/dictionary/getpwnam-entry.php,以及一个端口realpath
here http://www.cplusplus.com/reference/cstring/strchr/,但我仍然完全不知道如何处理这个问题。使用 MinGW,我仍然有一个主目录,表示为~
并位于/home/nate
,但由于它不是 POSIX,所以我没有pwd.h
帮助我找到这个主目录在哪里。
Q:如何移植以下功能才能与 MinGW 正常工作?
/**
* Return the canonicalized absolute pathname.
*
* It works exactly the same with realpath(3), except this function can handle the path with ~,
* where realpath cannot.
*
* @param path The path to be resolved.
* @param resolved_path Buffer for holding the resolved_path.
* @return resolved path, NULL is the resolution is not sucessful.
*/
gchar*
truepath(const gchar *path, gchar *resolved_path){
gchar workingPath[PATH_MAX];
gchar fullPath[PATH_MAX];
gchar *result=NULL;
g_strlcpy(workingPath,path,PATH_MAX);
// printf("*** path=%s \n",path);
if ( workingPath[0] != '~' ){
result = realpath(workingPath, resolved_path);
}else{
gchar *firstSlash, *suffix, *homeDirStr;
struct passwd *pw;
// initialize variables
firstSlash = suffix = homeDirStr = NULL;
firstSlash = strchr(workingPath, DIRECTORY_SEPARATOR);
if (firstSlash == NULL)
suffix = "";
else
{
*firstSlash = 0; // so userName is null terminated
suffix = firstSlash + 1;
}
if (workingPath[1] == '\0')
pw = getpwuid( getuid() );
else
pw = getpwnam( &workingPath[1] );
if (pw != NULL)
homeDirStr = pw->pw_dir;
if (homeDirStr != NULL){
gint ret=g_sprintf(fullPath, "%s%c%s", homeDirStr, DIRECTORY_SEPARATOR, suffix);
if (ret>0){
result = realpath(fullPath, resolved_path);
}
}
}
return result;
}