Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Saving file with unicode name problem - How to save UTF-8 filenames correctly in a crossplatform manner?

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

where

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

Update: with help I now have

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

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

like image 400
Rella Avatar asked Aug 07 '11 19:08

Rella


1 Answers

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

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.

like image 125
Nicol Bolas Avatar answered Oct 15 '22 13:10

Nicol Bolas