使用 r+ 模式打开文件时如何删除文件内容?

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

我已使用 r+ 模式打开我的文件。我对它做了一些改动,我想删除它从 X 到文件末尾的内容。

不幸的是,我不知道该怎么做。我一直在浏览文档,但没有提到这一点。

我不想将 :space: 写入文件,所以它 "looks" 就像它被清除一样,我也想把它变小。

在这种情况下,无法使用 w 打开文件。

r+模式打开文件会保留当前内容;因此,我认为没有办法使用 Lua 中可用的函数来截断文件的其余部分。这个SO answer表示可以用reopenw+来完成,但是既然你表示不能打开写,我觉得没有是一种做你想做的事的方法.

对该脚本的测试生成 new contentext(其中 ext 是之前内容的剩余部分):

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()

根据我的经验,我发现在 Lua 中截断文件的唯一方法是将内容写入 [=11= 中的辅助文件] 模式,然后重命名辅助文件以覆盖原始文件。当然,您可能希望根据文件的大小谨慎使用此方法。

在这个例子中"path"是原始文件的路径

local file, err = io.open( path + ".tmp", "w+" )
if not file then return end

file:write( truncated_data )
file:close( )

assert( os.rename( path + ".tmp", path ) )