Nat*_*enn 3 c unix windows mingw posix-api
我正在尝试使用MinGW 编译libUnihan代码,但是遇到了需要移植的函数.该函数的目的是获得规范路径表示.它使用pwd.h(这是POSIX,而MinGW不是)因此它可以通过检索passwd包含的结构来解释使用'〜'来表示主目录pw_dir.我发现一些信息在这里,和一个端口realpath 在这里,但我仍然完全处于亏损至于如何处理这个.使用MinGW,我仍然有一个主页目录,~并且位于/home/nate,但由于它不是POSIX,我不必pwd.h帮我找到这个主目录的位置.
问:如何将下面的功能移植到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;
}
Run Code Online (Sandbox Code Playgroud)
目的是实现~[username]/重映射逻辑.这种代码在Linux/UNIX环境中很有意义,但最常见的用途是引用用户自己的主目录.
为了方便起见,我只是添加对常见情况的支持~/- 即当前用户,而不是支持更一般的情况 - 在这种情况下它会失败并出现明显的错误.
获取当前用户主目录的功能是SHGetFolderPath.
#include <windows.h>
char homeDirStr[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, homeDirStr))) {
// Do something with the path
} else {
// Do something else
}
Run Code Online (Sandbox Code Playgroud)
如果用户查找失败,您粘贴的代码不会尝试替换该字符串,而只是返回NULL,因此您可以模拟它.