I have some internal file which can only be appended to and after each appending \n
character is added to the file. But theoretically it is possible that appending to the file is failed and it becomes corrupted. That is why every time when opening the file I want to seek to its last valid, after last EOL, position. This code will do that:
// Not using ios::app instead of ios::ate | ios::out because it will
// put print pointer to the EOF every time before writing.
fstream file(name.c_str(), ios::binary | ios::ate | ios::out | ios::in);
if(!file.is_open()) {
cerr << "Error in oppening file " << name << endl;
exit(EXIT_FAILURE);
} else {
while(0 != file.tellp()) //if file is not empty
{
file.seekg(-1, ios_base::cur);
if(0 == file.tellg() || file.get() == '\n') {
break;
}
file.seekg(-1, ios_base::cur);
}
file.seekp(of.tellg());
}
//{1}
//Use file for appending to...
But it wouldn't work fine if the length of part which should be appended to the file is lower than the length of part starting from the last EOL character in the file. That is why in {1}
position I want to delete file content starting from file.tellp() to the end.
How can I do that?