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;
}
windows 遍历目录
最新推荐文章于 2025-09-17 16:53:04 发布
1430

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



