使用fmt::output_file写入格式化wstring编译报错,如何解决?
解决fmt::output_file处理std::wstring日志的编译错误
我尝试用fmt库将格式化后的wstring日志写入文件,目前用fmt::format(...)和fmt::vprint能实现功能,但想用fmt::output_file时出现编译错误。以下是可行和不可行的代码实现:
... #include <fmt/format.h> #include <fmt/xchar.h> #include <fmt/os.h> template <typename... Args> static void Helper(const std::wstring& str, const Args&... args) { std::filesystem::create_directories("C:\\Logs"); std::filesystem::path file_path("C:\\Logs\\dll"); std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; auto file_path_utf8 = converter.to_bytes(file_path.wstring()); // Method 1 Working std::wofstream f_stream(file_path.string().c_str(), std::ios::app); f_stream << fmt::format(str, args...); // Method 2 Working std::FILE* file = std::fopen(file_path.string().c_str(), "a"); fmt::vprint(file, str.c_str(), fmt::make_wformat_args(args...)); std::fclose(file); // Method 3 NOT WORKING auto file = fmt::output_file(file_path.string().c_str(), fmt::file::WRONLY | fmt::file::CREATE | fmt::file::APPEND); file.print(str, args...); }
编译时触发错误:
error C2664: 'void fmt::v9::ostream::print<>(fmt::v9::basic_format_string<char>)': cannot convert argument 1 from 'const std::wstring' to 'fmt::v9::basic_format_string<char>'
问题根源
fmt::output_file是fmt::basic_output_file<char>的别名,默认处理窄字符流;而你的格式化字符串是宽字符类型的std::wstring,类型不匹配导致编译失败。
两种解决方案
方案一:先格式化再转码输出
先用fmt::format完成宽字符格式化,再将结果转成窄字符写入文件:// 修改后的Method 3 auto formatted_wstr = fmt::format(str, args...); std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; auto narrow_str = converter.to_bytes(formatted_wstr); auto file = fmt::output_file(file_path.string().c_str(), fmt::file::WRONLY | fmt::file::CREATE | fmt::file::APPEND); file.print("{}", narrow_str);方案二:直接使用宽字符输出流
改用fmt::basic_output_file<wchar_t>创建宽字符文件对象,直接处理宽格式字符串:// 修改后的Method 3 auto file = fmt::basic_output_file<wchar_t>(file_path.wstring().c_str(), fmt::file::WRONLY | fmt::file::CREATE | fmt::file::APPEND); file.print(str, args...);这种方式无需额外转码,效率更高,适合原生宽字符场景。
内容的提问来源于stack exchange,提问作者Stew
相关产品推荐
相关产品推荐

