I have a program where a user can write (append) to a chosen text file for storing information. Each line should be two numbers, and a date string (YYYY-MM-DD). There a multiple different text files that the program might write to, say "foo.txt" "bar.txt", "stroustrup.txt," and the file contents might look like this:
-18 30 2025-02-12
0 0 2025-02-01
-23 36 2025-02-27
Now I would like to add a sort of "undo" function, which deletes the last line from a chosen text file, in case the user input something erroneous, i.e. undo(const string& filename).
I know one possibility is to use getline(file,string) continuously, until reaching end of file, and writing everything but the last entry to a new file, thus creating a copy with the final line omitted. I feel like there should be a better way of doing this, however. As 1. I would have to create a new file, with a new name, for every call of my undo. And rewriting an entire file just to get rid of one line - one that is always at the very end even - seems wasteful.
Using seek() functions is also inappropiate, since the whole point is to delete erroneous input, I can't reasonably search for one particular string (since the user could input whatever silly string into the .txt file, before trying to undo).
Is there a neat way of doing this, i.e. replacing the final line with empty space or "\n", without having to copy and rewrite the entirety of the other contents?
truncateis your friend.getline()through the file, taking note of thetellg()position of the last line read until you get to the end. Then just truncate the file to the lasttellg()position.std::filesystem::resize_filecan truncate files as of C++17