How to delete the contents of a file after the last EOL?

I have an internal file that can only be added after each additional character is added \nto the file. But it is theoretically possible that the addition to the file is not performed, and it becomes damaged. That's why every time I open a file, I want to find its last valid, after the last EOL, position. This code will do this:

// 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 this will not work if the length of the part to be added to the file is less than the length of the part, starting with the last EOL character in the file. Therefore, in the position, {1}I want to delete the contents of the file, starting from file.tellp () to the end.

How can i do this?

+3
source share
2 answers

(. ).

POSIX, ftruncate (. ), . ++ (. )

+1

, . , . - , , .

( ), , 0x1A . Unix, .

. , , , , - , '\0'. (, , , 0x1A, - undefined. .)

( , CRC ; , CRC .)

+1

All Articles