Search code examples
filefile-ioluafile-manipulation

How to remove contents of the file when opened using r+ mode?


I've got my file open using r+ mode. I've made some alteration to it, and I would like to remove the contents of it starting from X to the end of the file.

Unfortunately I have no clue how to do that. I've been browsing through the docs, but there's no mention of that.

I don't want to write :space: to the file so it "looks" like it's cleared, I would like to make it smaller as well.

Opening the file using w is not an option in this case.


Solution

  • Opening a file with r+ mode preserves the current content; as the result, I don't think there is a way to truncate the rest of the file using the functions available in Lua. This SO answer indicates that it can be done using reopen with w+, but since you indicated that you can't open it for writing, I don't think there is a way to do what you want.

    Testing on this script produces new contentext (where ext is the leftover from the earlier content):

    local f = io.open("somefile", "w")
    f:write("some long text")
    f:close()
    
    local f = io.open("somefile", "r+")
    f:write("new content")
    f:close()