Skip to content

Open a text file for reading and writing #1413

Answered by ianthehenry
MaxGyver83 asked this question in Q&A
Discussion options

You must be logged in to vote

file/open is a wrapper around fopen, so :w and :w+ truncate the file as usual. If you want to open for reading and writing without truncating the file, use :r+.

Reading and writing the same file is a little bit cursed so it might be worth talking about the thing you're trying to do. It's usually better to read the whole file, edit its contents in memory, then write the new result out to a brand new file, and then os/rename it to overwrite the original file.

You can also use use :a+, but note that the file is positioned at the end initially, so you have to seek to the beginning ((file/seek filehandle :set 0)) before you can read anything out of it. And that doesn't let you reposition your …

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@MaxGyver83
Comment options

@sogaiu
Comment options

Answer selected by MaxGyver83
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants