1

I'm using TinyXML2 to load an xml document from disk.

The path of the file (configFileName) is a wstring and I am converting it to string like so:

    tinyxml2::XMLDocument doc;
    std::string fileName(configFileName.begin(), configFileName.end());
    doc.LoadFile(fileName.c_str());

This works but there may be times where my program runs on a double byte OS such as Chinese or Korean and the conversion from wstring to string above will loose the characters.

How can I load a path such as the following:

wstring wPathChinese = L"C:\\我明天要去上海\\在这里等我\\MyProgram";

EDIT

I have tried the following to convert the string but it still corrupts the chinese characters:

std::string ConvertWideStringToString(std::wstring source)
{
    //Represents a locale facet that converts between wide characters encoded as UCS-2 or UCS-4, and a byte stream encoded as UTF-8.
    typedef std::codecvt_utf8<wchar_t> convert_type;
    // wide to UTF-8
    std::wstring_convert<convert_type, wchar_t> converter;
    std::string converted_str = converter.to_bytes(source);

    return converted_str;
}

string pathCh2 = ConvertWideStringToString(wPathChinese);
Harry Boy
  • 4,159
  • 17
  • 71
  • 122
  • See my edit for what I have tried. Thanks. – Harry Boy May 13 '15 at 12:52
  • Can `std::string` hold these characters at all? – TobiMcNamobi May 13 '15 at 12:57
  • Now that you mention that no I dont think so. The doc.LoadFile accepts a "const char* filename" as its parameter. So I need to find a way to allow it to load a string with these characters if possible. – Harry Boy May 13 '15 at 13:00
  • If only `const char*` is allowed, I would consider to make sure you are using relative paths only instead of absolute path names that may contain any weird character. – TobiMcNamobi May 13 '15 at 13:06

1 Answers1

4

I suggest you to use the

XMLError tinyxml2::XMLDocument::LoadFile( FILE *)   

So you can simply do something like this:

FILE* fp = nullptr;
errno_t err = _wfopen_s(&fp, configFileName.c_str(), L"rb" );
if( fp && !err )
{
    tinyxml2::XMLDocument doc;
    doc.LoadFile( fp );
    fclose( fp );
}

And forget to do the nightmare conversion between wstring and string...

gugu69
  • 156
  • 7