May 12, 2021 Lua
The I/O library provides two modes for file operations. S imple mode has a current input file and a current output file, and provides actions related to those files. Full mode is implemented using an external file handle.
The I/O library treats the current input file as standard input (stdin) and the current output file as standard output (stdout).
So when we execute io.read, we read a line in the standard input.
Writing is simpler than reading, let's start with writing.
In the following example, the function io.write gets any number of string parameters and then writes them to the current output file.
local t = io.write("sin (3) = ", math.sin(3), "\n")
--> sin (3) = 0.1411200080598672
print("hello", "Lua"); print("Hi")
-->hello Lua
-->Hi
Note: Unlike the print function, the Write function does not attach any additional characters to the output, such as tabs, line breaks, and so on. T here is also the white function that uses the current output file, while the print always uses the standard output. I n addition, the print function automatically calls the tostring method of the argument, so the tables function and nil can be displayed.
Read function: Read string from the current input file, which controls what is read by its parameters:
Example:
--io.read 从标准输入流中获得,默认设置下,就是你的屏幕输入
t = io.read("*all")
t = string.gsub(t, ...) -- do the job
io.write(t) -- write the
Tip: If you use the luaEditor editor, it is estimated that you will not be able to enter it on the screen.
At the heart of the full pattern is the file handle. T he structure is similar to file flow (FILE) in the C language, which presents an open file and the current access location. T he function that opens a file is io.open. I t mimics the fopen function in the C language, which also requires opening the file name parameters of the file and opening the string parameters of the pattern:
Example:
--读操作
file = io.open("testRead.txt", "r")
for line in file:lines() do
print(line)
end
file:close()
--写操作
file = io.open("testRead.txt","a+")
file:write("\nhello")
file:close()
Material:
Content:
Results:
What's in the file: