[英]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.