I am currently reading a text file that has newlines occupying 2 bytes, since it writes newline as CRLF instead of only LF.
std::fstream fileReader = std::fstream(_filename, std::ios::in);
// READ THE SIZE OF THE FILE:
fileReader.seekg(0, fileReader.end); // set reader position to the end
std::streamsize fileSize = fileReader.tellg(); // get reader position
fileReader.seekg(0, fileReader.beg); // set reader position to the start
// SET UP THE BUFFER:
std::vector<char> buffer; buffer.resize(fileSize, '\0');
buffer.back() = '\0';
// READ:
fileReader.read(buffer.data(), fileSize);
The problem is that, "fileSize" IS actually the size of the file, not the amount of characters-that-are-not-CF in the file -which is what it's expecting.
Is there a way to get that number automatically?
Otherwise, I suppose binary mode is the only option left -though it would be pretty disappointing, as I was expecting proper automatic formatting when not using binary mode. Also, the .read function fails (fileReader's failbit is true)
This is normal behavior:
ifstream::read expects "the amount of characters that will be extracted" as a parameter, not the file size.
Since this amount is impossible to predict, and the function does not provide it either, using ifstream::read without the ios::binary flag is completely useless, unless the file is KNOWN to not contain any CF characters that will make ifstream freak out.
(I do not know if other characters also make ifstream freak out)
I suggest using the ios::binary in fstream, even for reading text files, to read them in one operation. Probably for writing files too (especially if you're on Windows).