Lua的IO库(Input/Output库)提供了对文件操作和标准输入输出的支持。以下是一些常用的IO库函数:

1. io.open(filename [, mode]):
   打开指定文件,并返回一个文件句柄。mode参数是一个字符串,指定文件的打开模式,例如:"r"(只读),"w"(写入),"a"(追加)等。
   local file = io.open("example.txt", "r")
   if file then
       print("File opened successfully")
       file:close()
   else
       print("Failed to open file")
   end

2. file:read([format1 [, ...]]):
   从文件中读取数据。可以指定读取的格式,也可以不指定。默认情况下,它读取一行文本。
   local file = io.open("example.txt", "r")
   if file then
       local line = file:read()
       print("Read from file:", line)
       file:close()
   else
       print("Failed to open file")
   end

3. file:write(...):
   向文件中写入数据。
   local file = io.open("example.txt", "w")
   if file then
       file:write("Hello, Lua!")
       print("Data written to file")
       file:close()
   else
       print("Failed to open file")
   end

4. io.input([file]) 和 io.output([file]):
   分别用于设置标准输入和标准输出的文件句柄。如果不提供参数,则返回当前的标准输入或标准输出文件句柄。
   io.output(io.open("output.txt", "w"))
   print("This will be written to output.txt")
   io.output():close()

   io.input(io.open("input.txt", "r"))
   local content = io.read("*all")
   print("Content of input.txt:", content)
   io.input():close()

5. file:seek([whence [, offset]]):
   设置文件位置指针。whence表示相对位置,可以是"set"(文件开头),"cur"(当前位置),或"end"(文件末尾);offset表示偏移量。
   local file = io.open("example.txt", "r")
   if file then
       file:seek("set", 5)
       local data = file:read("*a")
       print("Data from position 5:", data)
       file:close()
   else
       print("Failed to open file")
   end

这些是Lua中IO库的一些基本函数。你可以查阅官方文档以获取更多详细信息:[Lua 5.4 Reference Manual - 6.8 – IO Library](https://www.lua.org/manual/5.4/manual.html#6.8)。


转载请注明出处:http://www.pingtaimeng.com/article/detail/6519/Lua