Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to write a non-English string to a file and read from that file with C++?
    primarykey
    data
    text
    <p>I want to write a <code>std::wstring</code> onto a file and need to read that content as <code>std:wstring</code>. This is happening as expected when the string as <code>L"&lt;Any English letter&gt;"</code>. But the problem is happening when we have character like Bengali, Kannada, Japanese etc, any kind of non English letter. Tried various options like:</p> <ol> <li>Converting the <code>std::wstring</code> to <code>std::string</code> and write onto the file and reading time read as <code>std::string</code> and convert as <code>std::wstring</code> <ul> <li>Writing is happening (I could see from edito) but reading time getting wrong character</li> </ul></li> <li>Writing <code>std::wstring</code> onto wofstream, this is also not helping for native language character letters like <code>std::wstring data = L"হ্যালো ওয়ার্ল্ড";</code></li> </ol> <p>Platform is mac and Linux, Language is C++</p> <p>Code:</p> <pre><code>bool write_file( const char* path, const std::wstring data ) { bool status = false; try { std::wofstream file(path, std::ios::out|std::ios::trunc|std::ios::binary); if (file.is_open()) { //std::string data_str = convert_wstring_to_string(data); file.write(data.c_str(), (std::streamsize)data.size()); file.close(); status = true; } } catch (...) { std::cout&lt;&lt;"exception !"&lt;&lt;std::endl; } return status; } // Read Method std::wstring read_file( const char* filename ) { std::wifstream fhandle(filename, std::ios::in | std::ios::binary); if (fhandle) { std::wstring contents; fhandle.seekg(0, std::ios::end); contents.resize((int)fhandle.tellg()); fhandle.seekg(0, std::ios::beg); fhandle.read(&amp;contents[0], contents.size()); fhandle.close(); return(contents); } else { return L""; } } // Main int main() { const char* file_path_1 = "./file_content_1.txt"; const char* file_path_2 = "./file_content_2.txt"; //std::wstring data = L"Text message to write onto the file\n"; // This is happening as expected std::wstring data = L"হ্যালো ওয়ার্ল্ড"; // Not happening as expected. // Lets write some data write_file(file_path_1, data); // Lets read the file std::wstring out = read_file(file_path_1); std::wcout&lt;&lt;L"File Content: "&lt;&lt;out&lt;&lt;std::endl; // Let write that same data onto the different file write_file(file_path_2, out); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload