Lua os.remove()

前言#

今天来看的这个函数看似普通,但却花了我很多时间来调试,提前说明一下我使用的lua源代码的版本是5.1.4,版本这个东西很奇怪,明明这个版本很好用的函数,下个版本可能就删除了,很奇怪吧!今天我们看的这个函数也和版本有关。

内容#


os.remove()

  • 原型:os.remove (filename)
  • 解释:删除文件或一个空目录,若函数调用失败则返加nil加上错误信息。

Usage

  • 首先我们新建一个文件命名为removetest.lua编写如下代码:
-- 删除存在的文件
local rm_file = os.remove("remove_test.txt");
print("remove exist file ret:")
print(rm_file)
print("\n")

-- 删除不存在的文件
local rm_notexist_file = os.remove("remove_test2.txt");
print("remove don't exist file ret:")
print(rm_notexist_file)
print("\n")

-- 删除存在的目录
local rm_dir = os.remove("mydir")
print("remove exist dir ret:")
print(rm_dir)
print("\n")

-- 删除不存在的目录
local rm_notexist_dir = os.remove("mydir2")
print("remove don't exist dir ret:")
print(rm_notexist_dir)
print("\n")

-- 终极杀招 调用系统命令删目录
local cmd_rm = os.execute("rd mydir")
print("remove exist dir with sys cmd ret:")
print(cmd_rm)
if cmd_rm == 0 then
    print("remove exist dir with sys cmd success")
end
  • 运行结果:
Lua os.remove()_第1张图片
removefile.png
  • 关于运行结果的思考:

  • 由运行结果的前两组可以看出:当要删除的文件存在时,调用os.remove()会成功删除文件并且返回true,而当要删除的文件不存在时,函数返回nil这是符合预期结果的。

  • 由运行结果第3、4组可以看出无论要删除的目录是否存在,执行函数后均无法成功删除目录返回nil,这就值得思考了,明明文档里写了可以删除目录怎么到了这不行了呢,处于一脸懵逼的我不得不去查了一下lua的个各个版本的官方文档,结果更懵逼了。

    • 先来看看Lua 5.0,这压根就没提到可以删除目录的事情啊!!!

Deletes the file with the given name. If this function fails, it returns nil, plus a string describing the error.

- 然后是**Lua 5.1**,确实和我上面的解释是一样的。

Deletes the file or directory with the given name.Directories must be empty to be removed.If this function fails, it returns nil,plus a string describing the error.

  • 最后是完全相同的Lua 5.2、5.3,他居然提到了“POSIX systems”,那我使用的Windows岂不是没用了。

Deletes the file (or empty directory, on POSIX systems)with the given name.If this function fails, it returns nil,plus a string describing the error and the error code.

  • 顺着这个发现我又看了一下Lua 5.1版本的源码,调用的是c语言的int remove(char * filename);函数,网上搜了一下这个函数的解释为:“filename为要删除的文件名,可以为一目录。如果参数filename 为一文件,则调用unlink()处理;若参数filename 为一目录,则调用rmdir()来处理”。可是事实证明这在windows系统上也是不成立的,我在C语言中使用int remove(char * filename);函数去删除目录,得到的结果是没有权限,一开始我信了,然后我对要删除的文件夹进行了疯狂的权限修改,最终还是不能删除,然后我就想如果我自己创建的文件夹,你总该让我删了吧,于是我又调用c语言的mkdir()函数来创建了一个文件夹,然后再删除,得到的结果还是没有权限,这次我明白了,在windows系统下int remove(char * filename);这个函数或许就没有删除目录的功能,于是我释然了,祭出一件法宝,调用system("rd mydir")函数成功将目录删除,小样,还治不了你了!

总结#

  • os.remove(filename)正如他的参数名字一样,删除文件是没问题的,但是删除目录就看情况了。
  • 当遇到函数的运行结果和自己的预期不一致时,多去源头找找原因,比如翻翻官方文档。

你可能感兴趣的:(Lua os.remove())