#include <wtypesbase.h>
#include <tchar.h>
#include <string>
#ifdef _UNICODE
using _tstring = std::wstring;
#else
using _tstring = std::string;
#endif
_tstring DosPathToNtPath(const _tstring& strPath)
{
_tstring strResultPath;
TCHAR szDriveStrings[MAX_PATH] = { 0 };
TCHAR szDosBuf[MAX_PATH] = { 0 };
LPTSTR pDriveStr = NULL;
do
{
// 获取盘符名到缓冲
if (!::GetLogicalDriveStrings(_countof(szDriveStrings), szDriveStrings))
{
break;
}
// 遍历盘符名
for (int i = 0; i < _countof(szDriveStrings); i += 4)
{
pDriveStr = &szDriveStrings[i];
pDriveStr[2] = _T('\0');
// 查询盘符对应的DOS设备名称
DWORD dwCch = ::QueryDosDevice(pDriveStr, szDosBuf, _countof(szDosBuf));
if (!dwCch)
{
break;
}
// 结尾有 2 个 NULL, 减去 2 获得字符长度
if (dwCch >= 2)
{
dwCch -= 2;
}
if (strPath.size() < dwCch)
{
break;
}
// 路径拼接
if (_T('\\') == strPath[dwCch] && 0 == _tcsncmp(strPath.c_str(), szDosBuf, dwCch))
{
strResultPath = pDriveStr;
strResultPath += &strPath[dwCch];
break;
}
}
} while (false);
return strResultPath;
}
_tstring NtPathToDosPath(const _tstring& strPath)
{
_tstring strResultPath;
TCHAR szDosBuf[MAX_PATH] = { 0 };
do
{
if (strPath.size() < 2)
{
break;
}
// 非 NT 路径则不处理
if (_T(':') != strPath[1] || _T('\\') == strPath[0])
{
break;
}
// 查询盘符对应的DOS设备名称
if (!::QueryDosDevice(strPath.substr(0, 2).c_str(), szDosBuf, _countof(szDosBuf)))
{
break;
}
strResultPath = szDosBuf;
strResultPath += strPath.substr(2);
} while (false);
return strResultPath;
}
int main()
{
TCHAR szCurPath[MAX_PATH] = { 0 };
::GetModuleFileName(NULL, szCurPath, _countof(szCurPath));
_tstring strDosPath;
_tstring strNtPath = szCurPath;
strDosPath = NtPathToDosPath(strNtPath);
strNtPath = DosPathToNtPath(strDosPath);
return 0;
}


7636

被折叠的 条评论
为什么被折叠?



