I am still thinking a bit too C++'ish. So I presumed I needed to read the file first, and then write to it. I actually just wanted to append some text to the .gitignore file, so I ended up with this:
I read the Rust Docs a bit too uncarefully, thought the append option would imply read and write permissions
I probably am going to do some file reading with my current project, so this is a very useful lesson for me. Thanks again!
I’m generally partial to read-write-rename over append mode, for two reasons.
First: modifying a file in place is a lot more likely to corrupt the file if your program is terminated mid-write by an oomkill, power failure, or some other unavoidable outside problem. Individual writes are not atomic, and any portion, including the least convenient, may actually be committed to disk in that situation. With gitignore this isn’t so bad, as the file is text and the user can easily repair the damage, but it is avoidable and it’s good practice for when it’s more urgent.
Second: the “append” file mode is usually implemented by the OS to behave quite differently from opening in write mode and seeking to the end. In particular, each write occurs at the end of the file regardless of attempts to seek backwards, and taking writes by other programs into account invisibly. (It’s largely meant for logs.) This degree of OS magic can be surprising and is often counterintuitive. If it works for you, great - but be sure you understand what you’re asking the OS to do.
Instead, consider reading in the whole file, modifying it in memory, writing it out to a temporary file in the same directory, and renaming the file over the original. Renames within a filesystem are generally atomic, ensuring that no program sees a partial change - even if your power goes out.