How to both read and write a file in Lua?

Viewed 46

I would like to know if it is possible to open a file for both reading and writing.

f = assert(io.open("words", "r"))
t = f:read("a")
t = string.gsub(t, "Bad", "Good")
f = assert(io.open("words", "w"))
f:write(t)
f:close()

The above code seems to be working as expected. Sometimes what seems to work is not valid. For example, in some Unix pipelines, data is swallowed by one of the commands in an unintended fashion.

1 Answers

Either close the old f before you open the new one, or open it with mode r+ instead of r and seek back to the beginning before you write it back out.

Related