[英]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*
作为文件名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.