Lua Tutorial (15): Input Output library (I/O library) _lua

Source: Internet
Author: User
Tags assert function prototype lua

The I/O library provides two different models for file operations, a simple model and a complete model. The simple model assumes a current input file and a current output file, and his I/O operations are used for these files. The full model uses an explicit file handle and defines all operations as methods on the file handle.
1. Simple model:
The I/O library takes the process standard input output as its default input and output files. We can change the current input and output file by Io.input (filename) and io.output (filename) functions.
1). Io.write function:
The function prototype is Io.write (...). This function writes all the parameter order to the current output file. Such as:

Copy Code code as follows:

Io.write ("Hello", "World")--write out the content for HelloWorld

2). Io.read function:
The following table gives the definition and functional description of the function parameter:

Calling Io.read ("*all") reads all the contents of the current input file, starting with the current position. If the current position is at the end of the file, or if the file is empty, the call returns an empty string. Because LUA can efficiently handle long strings, it is possible in Lua to read the data out of the file first, and then perform various processing through the functions provided by the LUA string library.

Calling Io.read ("*line") returns the next row of the current file, but does not contain line breaks. When the end of the file is reached, the call returns to nil. Such as:

Copy Code code as follows:

For count = 1,math.huge do
Local line = Io.read ("*line")--if the argument is not passed, the default value is also "*line"
if line = = Nil Then
Break
End
Io.write (String.Format ("%6d", count), line, "\ n")
End

If you are simply iterating over all the rows in the file, you can use the Io.lines function to access each row of data in the file as an iterator, such as:

Copy Code code as follows:

Local lines = {}
For line in Io.lines () doing-accessing each data through an iterator
lines[#lines + 1] = line
End
Table.sort (lines)--sort, a function provided by the table Library of the LUA standard library.
For _,l in Ipairs (lines) do
Io.write (l, "\ n")
End

Calling Io.read ("*number") reads a number from the current input file. At this point, read will return a number directly, not a string. The "*number" option ignores all the spaces in front of the number and can handle numeric formats such as 3 and +5.2. If the data currently being read is not a valid number, read returns NIL. When you call read, you can specify multiple options, and the function returns the corresponding content based on each option argument. Such as:

Copy Code code as follows:

--[[
6.0-3.23 1000
... ...
The following code reads the number in the comment
--]]
While True
Local n1,n2,n3 = Io.read ("*number", "*number", "*number")
If not N1 then
Break
End
Print (Math.max (N1,N2,N3))
End

Calling Io.read (<num>) reads up to n characters from the input file and returns nil if no characters are read. Otherwise, the read string is returned. Such as:

Copy Code code as follows:

While True
Local block = Io.read (2^13)
If not block then
Break
End
Io.write (Block)
End

Io.read (0) is a special case for checking whether the end of the file is reached. If not, return an empty string, otherwise nil.

2. Full I/O model:

The full I/O model in Lua is used in much the same way as the C Run-time Library's file manipulation functions, which are all based on file handles.

1). Open the specified file through the Io.open function. and the open mode of the file is given in the parameter, where "R" means read, "W" means overwrite write, that is, first delete the original contents of the file, "a" is an append write, "B" means to open the file in binary mode. After the file is successfully opened, the function returns the handle that represents the file, and all subsequent operations based on the file need to pass the handle as a parameter. If open fails, return nil. Where the error message is returned by the second parameter of the function, such as:
ASSERT (Io.open (Filename,mode))--If the open fails, assert prints the error message given by the second argument.

2. File read-write function Read/write. Here you need to use the colon syntax, such as:

Copy Code code as follows:

Local F = assert (Io.open (filename, "R"))
Local T = f:read ("*all")--for read, its parameters are exactly equivalent to the parameters of read under the simple model.
F:close ()

In addition, the I/O library provides 3 predefined file handles, namely Io.stdin (standard input), io.stdout (standard output), Io.stderr (standard error Output). Such as:
Io.stderr:write ("This is a error message.")
In fact, we can also mix simple and complete patterns, such as:

Copy Code code as follows:

Local temp = Io.input ()-Saves the current file handle
Io.input ("Newinputfile")--open a new input file
Io.input (): Close ()--Closes the current file
Io.input (temp)--Restores the original input file

3). Performance tips:

Because it is faster to read the entire file at once than read-by-line, but for larger files, this is not feasible, so LUA provides a tradeoff between reading the specified number of bytes of data at a time, and, if the last row in the current read is not a complete row, you can also read the remainder of the row in that way. This will ensure that the data read is the whole row of data, so as to facilitate the processing of the upper logic. Such as:
The Local lines,rest = F:read (bufsize, "*line")--rest variable contains portions of the last row that are not read.

Here is a simple implementation of the WC command in the shell.

Copy Code code as follows:

Local bufsize = 8192
Local F = io.input (Arg[1])--Open input file
Local CC, LC, WC, = 0, 0, 0--count characters, lines, and words respectively
While True
Local lines,rest = F:read (bufsize, "*line")
If not lines then
Break
End
If rest Then
lines = lines. Rest.. "\ n"
End
CC = CC + #lines
--Calculate the number of words
Local _, T = String.gsub (lines.) %s+ "," ")
WC = WC + t
--Calculate the number of lines
_,t = String.gsub (line, "\ n", "\ n")
LC = LC + T
End
Print (LC,WC,CC)

4). Other file operations:

such as the Io.flush function flushes data from the IO cache to the disk file. The Io.close function closes the currently open file. The Io.seek function is used to set or get the read-write location of the current file, its function prototype is F:seek (Whence,offset), and if the whence value is "set", the value of offset is expressed as an offset relative to the starting position of the file. If it is "cur" (the default), offset is relative to the current position, such as "end", and the offset from the ending of the file. The return value of a function is independent of the whence parameter and always returns the current position of the file, that is, the number of offset bytes at the beginning of the file. The default value for offset is 0. Such as:

Copy Code code as follows:

function fsize (file)
Local present = File:seek ()--Get current position
Local size = File:seek (' End ')--Get file size
File:seek ("set", current)--restores the existing position
return size
End

Finally, if an error occurs, all of these functions return nil and an error message.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.