I was trying to implement a simple text editor and was met with this problem. When using std::wofstream to save buffer to file, I keep a WEOF at the end of the buffer for convenience of other parts in the program.
This works just fine with normal char(1 byte), but when it comes to wchar_t, wosftream::close() throws the exception as follow:
what(): basic_filebuf::_M_convert_to_external conversion error: iostream error
After certain tests, I am sure that it is WEOF that causes the problem, and the following code can reproduce it:
#include <fstream>
int main() {
std::wofstream fout("test.out");
std::wstring text = std::wstring(L"abc") + wchar_t(WEOF);
fout << text;
fout.close();
return 0;
}
An exception will be raised at 'fout.close()'. By removing '+ wchar_t(WEOF)', everything goes fine.
Notice that fout.is_open() holds, i.e., the file is opened successfully.
Environment : WSL : gcc version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04) --std=c++17
It looks quite similar to the bug mentioned here, which is marked as a RESOLVED FIXED bug on GNU.
Surely that I can substitute WEOF with '\0' as an end signal to avoid this problem, but I am wondering what's the mechanism behind the problem, and if there is a way to fix it without tricky methods involved.