Home > Net >  How to clear std::ofstream file buffer?
How to clear std::ofstream file buffer?

Time:11-24

I am making a console text editor that continuously saves its content to a text file as text is being written to the editor.

FileEditor editor("C://temp/test.txt");

while (true) {
     if (_kbhit()) {
        editor.keypress(_getche());
        system("cls");
        std::cout << editor.content();
        editor.save();
    }
}

In order to directly save the written content to the text file without having to close() and reopen() the file everytime, I flush the ofstream file buffer directly after inserting text into it.


class FileEditor {
private:
    std::ofstream _file;
    std::string _content;
public:

    // ...

    void save() {
        _file << _content << std::flush;
    }

    // ...

};

The problem is when I write multiple characters into the console, for example the string abcd, it will write a to the file, then aab, adding ab to the current buffer content, then aababc, and so on.

Therefore, I wish to clear the ofstream file buffer to replace its contents instead of continuously adding new text to the buffer. Is there a method for clearing the file buffer? Is there a better way of doing what I'm trying to achieve?

I tried finding a method for clearing the buffer and I tried searching online for anyone who might've had the same problem as me, but to no avail.

CodePudding user response:

The problem is when I write multiple characters into the console, for example the string abcd, it will write a to the file, then aab, adding ab to the current buffer content, then aababc, and so on.

Your problem has nothing to do with the file buffer. You are not clearing the editor buffer after writing it to the file, so you are writing the same characters to the file over and over.

The user types a, so your editor buffer is a, and you write a to the file.

Then, the user types b, so your editor buffer is now ab, and you write ab to the file.

Then, the user types c, so your editor buffer is now abc, and you write abc to the file.

Then, the user types d, so your editor buffer is now abcd, and you write abcd to the file.

And so on.

You need to write only the new characters that have entered the editor buffer since the last write to the file. For instance, maintain an index into the editor buffer where the last file write left off, and then have the next file write pick up from that index and advance it for the next file write, etc.

Therefore, I wish to clear the ofstream file buffer to replace its contents instead of continuously adding new text to the buffer. Is there a method for clearing the file buffer? Is there a better way of doing what I'm trying to achieve?

The only way to do this with ofstream is to close the re-open the file so that the current file content can be truncated. Otherwise, you will have to resort to using platform-specific APIs to truncate the file without closing it first.

  • Related