I have been struggling with some very simple code to write std::wstring to a file. From some research on stackoverflow it was reccomended that I should set the locale for the file before reading and writting.
typedef std::codecvt_utf8<wchar_t> ConverterType;
ConverterType converter;
// open a file in read mode.
std::wifstream readFile;
// pass in the current locale of the file and the converter
std::locale wloc(readFile.getloc(), &converter); //"en_US.UTF-8");
// imbue the file with the locale
readFile.imbue(wloc);
readFile.open(m_absoluteFilePath, std::ios::in | std::ios::binary);
if (!readFile.is_open())return false;
// read the data from the file
readFile >> readString;
// close the opened file.
readFile.close();
The above causes a R6025 error pure virtual function call. I found an online answer that suggested the following.
copy and paste from the page- "I've got the message "Runtim Error! Program: ... R6025 - pure virtual function call
The reason is that the stream's destructor accesses the facet again which has already been destructed. You can fix the code by shifting the creation of the facet before the creation of the stream." ...
null_wcodecvt wcodec(1);
std::locale wloc(std::locale::classic(), &wcodec);
std::wfstream file;
file.imbue(wloc);
I think this is exactly my problem, as when I remove the loc code entirely and just read and write to and from the file there is no error. The problem is I can't figure out how to move the wloc declaration prior to the wifstream declaration, since wloc is built using the readFile.getloc(). This seems to be a bit of a chicken and the egg situation to me?
What is the correct way to do this? It also seems strange to me that this dependancy of order does not seem to be well documented?
(On an additional note, I am reading and writting json strings to the file. My understanding is to use the std::ios::binary to simplify all the escape characters in the json string? perhaps this is untrue and a poor choice as I have not been able to test it, but I wanted to explain my choice of using std::ios::binary above.)
Aucun commentaire:
Enregistrer un commentaire