What is the best way to undo the writing to a file? If I'm going through a loop and writing one line at a time, and I want to undo the previous write and replace it with something else, how do I go about doing that? Any ideas?
Thanks in advance!
as others have noted, this doesn't make much sense, it's far better not to write until you have to. in your case, you can keep the 'writing pointer' one line behind your processing.
pseudocode:
previousItem = INVALID
for each item I:
is I same as previousItem?
then update previousItem with I
else
write previousItem to file
previousItem = I
write previousItem to file
as you can see, previousItem is the only item kept in memory, and it's updated to 'accumulate' as needed. it's only written to file when the next one isn't "the same as" that one.
of course, you could really rollback the file cursor, just keep track of the byte offset where the last line started and then do an fseek() to there before rewriting. at first it would seem simpler to code, but it's a total nightmare to debug.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With