Search code examples
c++wifstream

wstring read from .txt file doesn't print properly, but when written back to a file it's fine


I'm reading a wstring from .txt file using a while !eof loop:

std::wifstream fileStream(path);
std::wstring input;
 while (fileStream.eof() == false) {
 getline(fileStream, input);
 text += input + L'\n';
}

But when i print it in wcout some characters get turned into other ones. So far č has turned to e(with a backwards comma ontop), ě to i(with a backwards comma ontop) and š to an error character. First i suspected some format issue. But when i write the string to a new .txt file it's completely fine.

Also i'm using _setmode(_fileno(stdout), _O_U8TEXT); to get wcout to even work.


Solution

  • Solved by reading the file as binary and then converting to wstring using MultiByteToWideChar function from win32 api:

    std::ifstream fileStream(path, std::ios::binary | std::ios::ate);
    auto size = fileStream.tellg();
    fileStream.seekg(0, std::ios::beg);
    
    LPCCH memory = new CCHAR[size];
    
    fileStream.read((char*)memory, size);
    
    text.resize(size);
    MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, memory, size, (LPWSTR)text.c_str(), text.length());
    delete[] memory;