【发布时间】:2020-03-27 07:47:03
【问题描述】:
我有几个从命令行参数读取文件路径的 Windows 应用程序。一切都完美无缺,除非传递带有非 ANSI 字符的路径。我期待这个,但不知道如何处理它。可能是一个入门级的问题,但这让我抓狂。
我当前的代码如下:
int main(int argc, char* argv[]) {
namespace po = boost::program_options;
po::options_description po_desc("Allowed options");
po_desc.add_options()
("file", po::value<std::string>(), "path to file");
po::variables_map po_vm;
try {
po::store(po::parse_command_line(argc, argv, po_desc), po_vm);
po::notify(po_vm);
} catch (...) {
std::cout << po_desc << std::endl;
return false;
}
const std::string file_path = po_vm["file"].as<std::string>();
// ...
}
我发现如果我将file_path 的类型从std::string 替换为boost::filesystem::path,现在会读取一些路径。我不知道确切原因,但可以推断它必须与 Latin1 字符集的翻译有关。
例如,有以下文件:
malaga.txt
málaga.txt
mąlaga.txt
第一个总是正确读取,而第二个在使用 std::string file_path 而不是 boost::filesystem::path file_path 时失败。第三个总是失败。
我尝试将主函数切换为int main(int argc, wchar_t* argv) 并使用std::wstring 作为参数类型,但它与boost::program_options 解析器不兼容。
如何正确读取此类 Unicode 文件名?
【问题讨论】:
-
你读过Unicode支持 boost.org/doc/libs/1_71_0/doc/html/program_options/…
-
也许你需要先
chcp 65001? -
通过 chcp.com 设置控制台代码页与此无关。 Windows 中的本机命令行是 Unicode (UTF-16LE)。问题是 C 运行时的
main入口点解析来自GetCommandLineA的命令行的ANSI 编码,而不是来自GetCommandLineW的Unicode 命令行。非标准的wmain入口点基于本机Unicode 命令行。如果应用程序需要字节字符串,wchar_t字符串可以通过WideCharToMultiByte编码为 UTF-8。 -
谢谢大家,你们的cmets很有用!
标签: c++ windows unicode command-line-arguments boost-program-options