如何将const std::filesystem::directory_entry转换为TCHAR?求技术指导
解决std::filesystem::directory_entry转TCHAR的问题
我来帮你搞定这个转换问题!首先先指出你代码里的几个明显问题,再一步步讲清楚转换的实现方式。
先修正你代码里的错误
你提供的代码里有个语法错误:在lambda表达式里写了std::wstring = path.wstring();,这里既没有定义变量名,也没有正确引用directory_entry的路径对象。正确的写法应该是先通过dirent.path()获取路径,再调用对应的字符串方法,比如:
std::wstring wsPath = dirent.path().wstring();
转换为TCHAR的具体实现
TCHAR是Windows平台的宏,它的实际类型取决于项目是否定义了UNICODE宏:
- 当定义
UNICODE时,TCHAR等价于wchar_t - 未定义时,
TCHAR等价于char
所以我们可以利用std::filesystem::path提供的两种字符串接口来适配这两种情况:
情况1:定义了UNICODE(默认大多数Windows项目都是这种)
直接获取宽字符串版本,再通过c_str()得到const TCHAR*:
const TCHAR* tcharPath = dirent.path().wstring().c_str();
情况2:未定义UNICODE
获取窄字符串版本,再通过c_str()得到const TCHAR*:
const TCHAR* tcharPath = dirent.path().string().c_str();
通用封装(适配两种情况)
你可以写一个小函数来自动处理两种情况,避免重复判断:
#include <tchar.h> #include <filesystem> namespace fs = std::filesystem; const TCHAR* PathToTCHAR(const fs::directory_entry& dirent) { #ifdef UNICODE return dirent.path().wstring().c_str(); #else return dirent.path().string().c_str(); #endif }
修正后的完整代码
把这些逻辑整合到你的代码里,最终版本如下:
#include "pch.h" #include <memory> #include <filesystem> #include <algorithm> #include <iostream> #include <tchar.h> #include <string.h> typedef wchar_t WCHAR; namespace fs = std::filesystem; const TCHAR* PathToTCHAR(const fs::directory_entry& dirent) { #ifdef UNICODE return dirent.path().wstring().c_str(); #else return dirent.path().string().c_str(); #endif } int main() try { std::for_each(fs::recursive_directory_iterator("./foo/"), {}, [](fs::directory_entry const& dirent) { if (fs::is_regular_file(dirent) && dirent.path().filename() == "black.txt") { // 转换为TCHAR指针 const TCHAR* filePath = PathToTCHAR(dirent); // 可以在这里使用filePath,比如输出(注意用_tprintf适配TCHAR) _tprintf(_T("找到文件:%s\n"), filePath); } }); } catch (fs::filesystem_error const& e) { std::cerr << "error: " << e.what() << '\n'; }
注意事项
- 如果你需要把TCHAR指针保存下来而不是临时使用,记得要复制字符串内容,因为
wstring()和string()返回的是临时对象,它们的c_str()在对象销毁后会失效。比如可以用_tcscpy来复制到一个TCHAR数组里,或者用std::basic_string<TCHAR>来存储。 - 输出TCHAR字符串时,要使用对应的宽/窄字符输出函数,比如
_tprintf、WriteConsole等,避免字符编码不匹配的问题。
内容的提问来源于stack exchange,提问作者Pranciskus
相关产品推荐
相关产品推荐

