0

I want to write a specific byte inside a .txt file, for example: Text File

Something

Code

Som4thing

I want to do like that, but without overwriting the whole file using io.write().

I hope it was easy to understand my question.

1 Answer 1

2

First, you need to figure out what mode to open the file in. r won't let you write, so it's out. a and a+ will only ever let you write to the end, so they're out. w and w+ erase the whole file, so they're out. That leaves r+.

Next, you need to get to the right place in the file. The seek function does that. In your case, you want to go to 3 bytes past the beginning.

Finally, simply write your data and close the file.

local file = io.open('filename.txt', 'r+')
file:seek('set', 3)
file:write('4')
file:close()
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! I actually didn't know you could do f:write(), I always did io.input(f) io.write('4'). And I actually appreciate that you answer pretty fast.
I just noticed, the byte I want to open will be always the letter position minus 1?
@ProgrammingIsLearning Yeah, it's zero-based, unlike pretty much everything else in Lua.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.