std::ifstream sr(path.c_str());
if (!sr)
throw runtime_error("Could not open file '"+path+"\'");
sr.seekg(0, ios::end);
streampos lastPos = sr.tellg(); //returns 3161125
unsigned dataSize = (int)lastPos - 100; //dataSize becomes 3161025
char* data = (char*)malloc(dataSize);
if (!data)
throw runtime_error("Out of memory whean allocating read buffer");
sr.clear();
sr.seekg(0, ios::beg);
sr.read(data, dataSize); //sr.read(data, 3110000) works!
if(sr.fail()) //fails
This code fails, but if I read 3110000 bytes, the read() succeeds and fail() is false. I can load the file via stream iterators like this:
string data(std::istreambuf_iterator<char>(sr),
std::istreambuf_iterator<char>());
Any idea why read() fails?
The value returned by
seekg()+tellg()is reliable only if the file is opened in binary mode. In text mode line endings are translated, with a different result depending on the way your operating system stores files.Specifically, on Windows the CR+LF pair is translated to a single character
'\n'.