如何用C++标准库或Boost替换MFC CString及wchar_t相关定义代码
方案1:C++17 标准库实现(最推荐)
直接用C++17引入的std::filesystem路径处理库+std::wstring动态字符串,完全淘汰固定长度缓冲区和MFC CString依赖:
#include <windows.h> #include <filesystem> #include <string> namespace fs = std::filesystem; int main() { // 动态获取当前模块路径,无固定长度缓冲区限制 DWORD buf_len = MAX_PATH; std::wstring exe_path; do { exe_path.resize(buf_len); buf_len = GetModuleFileNameW(NULL, exe_path.data(), static_cast<DWORD>(exe_path.size())); } while (buf_len == exe_path.size()); exe_path.resize(buf_len); // 直接用filesystem拼接目标路径,无需手动拆分盘符、目录 fs::path target_path = fs::path(exe_path).parent_path() / L"myfile.dat"; // 后续如果需要字符串格式,直接调用即可: // std::wstring target_str = target_path.wstring(); // const wchar_t* target_cstr = target_path.c_str(); }
编译说明
MSVC编译时需要开启/std:c++17及以上版本的编译选项。
方案2:Boost 实现(兼容C++11/14等旧标准)
如果使用的编译器不支持C++17,可以替换为Boost.Filesystem库,逻辑和标准库实现几乎完全一致:
#include <windows.h> #include <boost/filesystem.hpp> #include <string> namespace fs = boost::filesystem; int main() { // 动态获取当前模块路径逻辑和标准库方案完全一致 DWORD buf_len = MAX_PATH; std::wstring exe_path; do { exe_path.resize(buf_len); buf_len = GetModuleFileNameW(NULL, exe_path.data(), static_cast<DWORD>(exe_path.size())); } while (buf_len == exe_path.size()); exe_path.resize(buf_len); fs::path target_path = fs::path(exe_path).parent_path() / L"myfile.dat"; }
编译说明
需要引入Boost头文件目录,链接Boost.Filesystem对应的预编译库。
核心改进点
- 完全淘汰固定长度的
wchar_t数组,std::wstring自动动态扩容,支持超过MAX_PATH长度的路径,无缓冲区溢出风险 - 无需手动调用
_wsplitpath_s这类C风格接口拆分路径,路径操作都由封装好的path类处理,代码可读性大幅提升 - 路径拼接自动处理分隔符,不需要手动加反斜杠,避免手动拼接的语法错误
- 所有字符串都是标准库类型,没有MFC依赖,跨项目复用性更强
内容的提问来源于stack exchange,提问作者Mario
相关产品推荐
相关产品推荐

