These are the things I cannot change:
- The language is C++
- However, the file is opened with the good old
fopen()
- The file is not opened in binary mode
This is what I have to do:
- Write a function that loads the entire file into a
std::string
. Lines should be separated only by\n
and not other variants.
This is what I did:
string ReadWhole()
{
Seek(0);
char *data = new char[GetSize()];
if (1 != fread(data, GetSize(), 1, mFile))
FATAL(Text::Format("Read error: {0}", strerror(errno)));
string ret(data, GetSize());
delete[] data;
return ret;
}
For reference, this is GetSize
, but it simply returns the size of the file (cached):
int GetSize()
{
if (mFileSize)
return mFileSize;
const int current_position = ftell(mFile);
fseek(mFile, 0, SEEK_END);
mFileSize = ftell(mFile);
fseek(mFile, current_position, SEEK_SET);
return mFileSize;
}
This is the problem
fread()
fails because the file has \r\n
line endings and they count as only 1 character instead of 2, so it tries to read more than the characters in the file.
I could fix it with fgets
but I was wondering if there was a better way. Thanks.