This is what I cannot change:
- C ++ language
- However, the file is opened using the old old
fopen() - File does not open in binary mode
This is what I have to do:
- Write a function that loads the entire file into
std::string. Lines should be split only \n, not other options.
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 just returns the file size (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 problem
fread()fails because the file has line endings \r\nand they are considered only 1 character instead of 2, so it tries to read more than the characters in the file.
I could fix this with help fgets, but I was wondering if there is a better way. Thank.