Lua File Io
# Lua File I/O
The Lua I/O library is used for reading and processing files. It is divided into a simple model (like C) and a complete model.
* The **simple model** has a current input file and a current output file, and provides operations related to these files.
* The **complete model** uses external file handles. It defines all file operations as methods of the file handle in an object-oriented manner.
The simple model is suitable for simple file operations. However, for advanced file operations, the simple model is insufficient. For example, operations like reading multiple files simultaneously are better suited for the complete model.
The syntax for opening a file is as follows:
file = io.open (filename [, mode])
The values for `mode` are:
| Mode | Description |
| --- | --- |
| r | Opens a file in read-only mode. The file must exist. |
| w | Opens a file in write-only mode. If the file exists, its length is cleared to 0, meaning its content will disappear. If the file does not exist, it is created. |
| a | Opens a file in append mode for writing only. If the file does not exist, it is created. If the file exists, the written data is appended to the end of the file, preserving the original content. (EOF marker is preserved) |
| r+ | Opens a file in read-write mode. The file must exist. |
| w+ | Opens a file in read-write mode. If the file exists, its length is cleared to 0, meaning its content will disappear. If the file does not exist, it is created. |
| a+ | Similar to `a`, but this file is readable and writable. |
| b | Binary mode. If the file is a binary file, you can add `b`. |
| + | The `+` sign indicates that the file can be both read and written. |
* * *
## Simple Model
The simple model uses standard I/O or uses a current input file and a current output file.
The following is the code for the `file.lua` file, operating on the file `test.lua` (if it doesn't exist, you need to create it). The code is as follows:
## Example
-- Open the file in read-only mode
file =io.open("test.lua","r")
-- Set the default input file to test.lua
io.input(file)
-- Print the first line of the file
print(io.read())
-- Close the opened file
io.close(file)
-- Open the file in append mode for writing only
file =io.open("test.lua","a")
-- Set the default output file to test.lua
io.output(file)
-- Add a Lua comment at the end of the file
io.write("-- test.lua file end comment")
-- Close the opened file
io.close(file)
Executing the above code, you will find that it prints the first line of information from the `test.lua` file and adds a Lua comment to the last line of that file. For example, my output is:
-- test.lua file
In the above example, we used `io."x"` methods. In `io.read()`, we did not pass any arguments. The argument can be one of the following from the table:
| Mode | Description |
| --- | --- |
| "*n" | Reads a number and returns it. Example: `file.read("*n")` |
| "*a" | Reads the entire file from the current position. Example: `file.read("*a")` |
| "*l" (default) | Reads the next line, returning `nil` at the end of the file (EOF). Example: `file.read("*l")` |
| number | Returns a string of a specified number of characters, or `nil` at EOF. Example: `file.read(5)` |
Other `io` methods include:
* **io.tmpfile():** Returns a temporary file handle, opened in update mode, which is automatically deleted when the program ends.
* **io.type(file):** Checks if `obj` is a valid file handle.
* **io.flush():** Writes all data in the buffer to the file.
* **io.lines(optional file name):** Returns an iterator function. Each call will get one line of content from the file. When the end of the file is reached, it returns `nil` but does not close the file.
* * *
## Complete Model
Usually, we need to handle multiple files at the same time. We need to use `file:function_name` instead of the `io.function_name` method. The following example demonstrates how to handle the same file simultaneously:
## Example
-- Open the file in read-only mode
file =io.open("test.lua","r")
-- Print the first line of the file
print(file:read())
-- Close the opened file
file:close()
-- Open the file in append mode for writing only
file =io.open("test.lua","a")
-- Add a Lua comment at the end of the file
file:write("--test")
-- Close the opened file
file:close()
Executing the above code, you will find that it prints the first line of information from the `test.lua` file and adds a Lua comment to the last line of that file. For example, my output is:
-- test.lua file
The parameters for `read` are the same as in the simple model.
Other methods:
* **file:seek(optional whence, optional offset):** Sets and gets the current file position. On success, it returns the final file position (in bytes). On failure, it returns `nil` plus an error message. The parameter `whence` can be:
* "set": From the beginning of the file.
* "cur": From the current position .
* "end": From the end of the file.
* offset: Default is 0.
Without parameters, `file:seek()` returns the current position. `file:seek("set")` positions to the beginning of the file. `file:seek("end")` positions to the end of the file and returns the file size.
* **file:flush():** Writes all data in the buffer to the file.
* **io.lines(optional file name):** Opens the specified file `filename` in read mode and returns an iterator function. Each call will get one line of content from the file. When the end of the file is reached, it returns `nil` and automatically closes the file.
Without parameters, `io.lines()` `io.input():lines()`; reads the content of the default input device but does not close the file at the end, for example:
for line in io.lines("main.lua") doprint(line)end
The following example uses the `seek` method to position to the 25th character from the end of the file and uses the `*a` parameter of the `read` method, which reads the entire file from the current position (25th character from the end).
## Example
-- Open the file in read-only mode
file =io.open("test.lua","r")
file:seek("end",-25)
print(file:read("*a"))
-- Close the opened file
file:close()
The result I got is:
st.lua file end--test
YouTip