windows 遍历目录


std::string wstringToString(const std::wstring& wstr) {
    // 使用宽字符到多字节转换
    if (wstr.empty()) {
        return "";
    }
    int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
    std::string str(size_needed, 0);
    WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &str[0], size_needed, NULL, NULL);
    return str;
}
std::wstring StringToWString(const std::string& str)
{
    int size_needed = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0);
    std::wstring wstr(size_needed, 0);
    MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, &wstr[0], size_needed);
    wstr.pop_back(); // 移除多出来的 null terminator
    return wstr;
}

//遍历某个目录
void directoryTree(const std::string& path, void(*func)(WIN32_FIND_DATA*))
{
    WIN32_FIND_DATA findFileData;
    HANDLE hFind = INVALID_HANDLE_VALUE;
    std::wstring searchPattern = StringToWString(path);
    hFind = FindFirstFile(searchPattern.c_str(), &findFileData);
    if (hFind != INVALID_HANDLE_VALUE)
    {
        do
        {
            func(&findFileData);
        } while (FindNextFile(hFind, &findFileData) != 0);
        FindClose(hFind);
    }
}

void func(WIN32_FIND_DATA* pFindFileData)
{
    std::wstring name = pFindFileData->cFileName;
    if (name == L"." || name == L"..") return;

    std::wcout << name << std::endl;
}
int main()
{
    //需要注意第一个参数必须有通配符*或者*.data
    directoryTree("c:\\*", &func);
    return 0;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值