DOS路径与NT路径转换(Win32, C++)

#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;
}

 38e58e14c4a84b0981f14c536c397b6f.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值