Lua basics [5] I/O file operations, lua Basics
-- [Lua file operation-related I/O] ---- You can specify to open a file in a specific directory. If the file does not exist, -- lua will help us create this file under the directory you specified, provided that the directory exists -- [we should also master the file writing mode; the following write mode is described: "r" Mode: Read mode (In this mode, only content can be read from the file, but cannot be written) "w": Write mode (write to the file is allowed, the content of the last file will be replaced by this write.) "a": Add mode "w +": update mode. All previous data will be cleared. "a + ": in update mode, all previous data is saved, and data can only be added at the end of the file] -- theFile = io. open ("C:/Users/Administrator/Desktop/2.lua"," w ") if theFile ~ = Nil thentheFile: write ("this is a lua file \ n") theFile: write ("I know \ n") theFile: write ("this is my test \ n ") -- close the file io after the operation. close (theFile) -- once the file is closed, it must be restarted before it can be entered, but the previous file content will be overwritten by myFile = io. open ("C:/Users/Administrator/Desktop/2.lua"," a + ") y = myFile: seek (" set ", 0) myFile: write ("it works \ n") myFile: write ("we are good friends") z = myFile: seek ("cur") x = myFile: seek ("end ") print (x, y, z) myFile: setvbuf ("no") myFile: flush () myFile: close (myFile) end -- output the file content in line for line in io. lines ("C:/Users/Administrator/Desktop/2.lua") doprint (line) end
-- [[File read] -- buf = myFile: read ("* all") print (buf)