用unicode文件名保存文件的问题-如何以跨平台的方式正确保存UTF-8文件名
C++ Saving file with unicode name problem - How to save UTF-8 filenames correctly in a crossplatform manner?
我想保存一个文件名为Привет Мир.jpg
的文件,我收到一个字符串(例如从文件中读取)(其中包含unicode),但我的c++代码将其保存为ÐÑÐ¸Ð²ÐµÑ ÐиÑ.jpg
我怎样才能正确地保存它呢?(顺便说一句,如果我只是将该字符串保存到文件中,它会正确保存,这意味着只有我保存文件名的方式是错误的。如何修复这个?)
下面是我保存文件的代码:
void file_service::save_string_into_file( std::string contents, std::string name )
{
std::string pathToUsers = this->root_path.string() + "/users/";
boost::filesystem::path users_path ( this->root_path / "users/" );
users_directory_path = users_path;
general_util->create_directory(users_directory_path);
std::ofstream datFile;
name = users_directory_path.string() + name;
datFile.open(name.c_str(), std::ofstream::binary | std::ofstream::trunc | std::ofstream::out );
datFile.write(contents.c_str(), contents.length());
datFile.close();
}
,
void general_utils::create_directory( boost::filesystem::path path )
{
if (boost::filesystem::exists( path ))
{
return;
}
else
{
boost::system::error_code returnedError;
boost::filesystem::create_directories( path, returnedError );
if ( returnedError )
{
throw std::runtime_error("problem creating directory");
}
}
}
更新:在帮助下,我现在有
void file_service::save_string_into_file( std::string contents, std::string s_name )
{
boost::filesystem::path users_path ( this->root_path / "users" );
users_directory_path = users_path;
general_util->create_directory(users_directory_path);
boost::filesystem::ofstream datFile;
boost::filesystem::path name (users_directory_path / s_name);
datFile.open(name, std::ofstream::binary | std::ofstream::trunc | std::ofstream::out );
datFile.write(contents.c_str(), contents.length());
datFile.close();
}
但是当我保存文件时,它保存的文件名为Привет РњРёСЂ.jpg
所以…我现在该怎么办呢?
c++标准库不支持Unicode。因此,您必须使用支持Unicode的库(如Boost.Filesystem)。
或者,您必须处理特定于平台的问题。Windows支持UTF-16,所以如果你有UTF-8字符串,你需要将它们转换为UTF-16 (std::wstring)。然后将它们作为文件名传递给iostream文件打开函数。Visual Studio版本的文件流可以使用wchar_t*
作为文件名。
相关文章:
- 从命令行c++发送文本文件名
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 通过网络、跨平台传递std::变体是否安全
- 当Microsoft文档仅包含 C# 示例时,如何查找 C++ 包含文件名
- 如何跨平台将二进制资源构建到程序中?
- 如何在CPP的给定目录中列出UTF编码的文件名?
- 在Visual Studio 2019中保存时ReadDirectoryChangesW文件名的问题
- C++:在Windows中浏览名称中带有点的文件名
- 我在 ifstream input_file(文件名)行中收到错误"no matching function to call";
- 不带预处理器的调用方法/文件的文件名/行号
- 在 C++ 中为文件名添加时间戳
- 为什么当我在 std::string 中打开文件名的 fstream 时出现"no matching function"错误?
- 以跨平台的方式将图像源路径从C++发送到 QML
- 跨平台 GPU 计算
- 在哪里存储跨平台C++应用存储?
- 如何将文件名作为参数传入并正确打开?
- 如何在目录及其子文件夹中构建文件名字符串向量?
- 要求用户输入C++输出文件名
- 用unicode文件名保存文件的问题-如何以跨平台的方式正确保存UTF-8文件名