C ++保存具有Unicode名称问题的文件-如何以跨平台方式正确保存UTF-8文件名? [英] C++ Saving file with unicode name problem - How to save UTF-8 filenames correctly in a crossplatform manner?

查看:112
本文介绍了C ++保存具有Unicode名称问题的文件-如何以跨平台方式正确保存UTF-8文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保存一个名称为Привет Мир.jpg的文件,我收到一个字符串(例如,从文件中读取)(其中包含unicode),但是我的C ++代码将其保存为ÐÑÐ¸Ð²ÐµÑ ÐиÑ.jpg 我该怎么做才能正确保存它? (顺便说一句,如果我只是将字符串保存到文件中,它将正确保存,这意味着仅保存文件名的方式有些错误.如何解决此问题?)

I want to save a file with name Привет Мир.jpg I receive a string (read it from file for example) (with unicode in it) but my C++ code saves it as ÐÑÐ¸Ð²ÐµÑ ÐиÑ.jpg What shall I do to save it correctly? (btw if I just save that string into file it saves correctly, meaning only the way I save filename is some whay wrong. How to fix this?)

这是我保存文件的代码:

Here is my code for file saving:

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");
        }
    }
}

更新:

但是当我保存文件时,它将文件名另存为Привет РњРёСЂ.jpg...现在我该怎么办?

But when I save file it saves its file name as Привет Мир.jpg so.. What shall I do now?

推荐答案

C ++标准库不支持Unicode.因此,您必须使用支持Unicode的库(例如Boost.Filesystem).

The C++ standard library is not Unicode aware. Therefore, you must use a library (like Boost.Filesystem) that is Unicode aware.

或者,您必须处理特定于平台的问题. Windows支持UTF-16,因此,如果您有UTF-8字符串,则需要将它们转换为UTF-16(std :: wstring).然后,将它们作为文件名传递给iostream文件打开功能. Visual Studio版本的文件流可以使用wchar_t*作为文件名.

Alternatively, you have to deal with platform-specific issues. Windows supports UTF-16, so if you have UTF-8 strings, you need to convert them to UTF-16 (std::wstring). Then you pass those as filenames to the iostream file opening functions. Visual Studio's version of the file streams can take a wchar_t* for the filename.

这篇关于C ++保存具有Unicode名称问题的文件-如何以跨平台方式正确保存UTF-8文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆