Open a text file for reading and writing #1413
-
When I open a text file in mode (def filehandle (file/open "/tmp/file" :w))
(var line nil)
(while true
(set line (file/read filehandle :line))
(print (if line (string "line: " line) "Empty file!"))
(unless line (break)))
(file/close filehandle) Even worse: After trying to print all lines, the file content is deleted. (Only with Isn't it possible to open a file for reading and writing? Do I have to open a file twice in such a case? If I want to read and write multiple times in a loop, can I keep the file open twice (for reading and for writing)? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
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 You can also use use |
Beta Was this translation helpful? Give feedback.
file/open
is a wrapper aroundfopen
, 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 …