How can I tell if a file has changed?

I am trying to write a text program to handle huge files. Now when the user closes the file, I would ask them "Do you want to save the file" if the file has changed.

I am implementing this using a dirty bit that is set whenever the user performs any write operations.

However, this has the limitation that a file will be considered dirty unless it is actually dirty. For example, if the user types a character and deletes it, the file is not changed. However, my implementation of the dirty bits thinks it has changed.

What's the best way, in terms of speed, to determine if a file has actually changed?

Full bit-to-bit comparison for the whole file is too slow . (Comparing the hash of a file is also too slow because the entire file has to be processed to compute the hash. Performing a length comparison first before comparing the values ​​works when the lengths are different, but fails when they aren't, as in my example above.)

+3


source to share


1 answer


Since it is a word processor program, it can also have a history of actions. You can maintain 2 stacks, one for historical actions (changes that were already included) and the other for future actions (changes that were applied but have now been reverted in a linear fashion).

For example, each character typed in a sequence can be one item on the action stack, and dividing it can be equivalent to pushing that action off the history stack onto the future action stack (repeat actions if necessary).



Now, whenever the history action stack is not empty, you prompt the user to close the file on close.

For simplicity, you can have a limited number of history items (say the last 100 actions). Then, since every addition / subtraction to the document happens with every user action, there is hardly any delay, and figuring out whether it is empty or not is an O (1) operation.

+1


source







All Articles