Quick Master Lua 5.3--I/O Library (2)

Source: Internet
Author: User
Tags control characters truncated

Q: What is the "complete Model"?

A: All file operations are based on explicitly specified file handles and can open multiple file handles at the same time. This means that multiple files can be manipulated at the same time, and can be read or written for each file. The file handle is equivalent to "file*" in the C language, which represents the current read location of an open file. io.open()You can specify an open file and return its file handle,

--[[io.open (filename [, mode]) opens the file "filename" in "mode", returning its file handle.     "Mode" has the following options, features the same function as the "mode" parameter of "fopen ()" In C language: "R": Open as read-only, the file does not have the times wrong (when not specified, this option is used by default), "W": Open as write-only, if the file exists, empty the file; "A": Open in addition to write-only, if the file does not exist, the file will be created, if the file exists, the data written will be added to the end of the file, that is, the original content of the file will be retained (the original EOF characters are retained); "r+": Open in read-write mode, the file does not exist w+ ": Open in a read-write manner, if the file exists, empty the file, otherwise create the file;" A + ": Open in an additional read-write mode, if the file does not exist, the file will be created, if the file exists, the data written will be added to the end of the file, that is, the original content is retained ( "Nil" + error message + error code when an error occurs. ]]Print(io. Open ("File","R"))--"file" does not exist. -- nil file:no such file or directory 2Localf =io. Open ("File","w+")--Create "file" files. F:write ("Hello world!") F:close ()--[["file" files: Hello world!]]Print(io. Open ("/etc/passwd","W"))- Nil/etc/passwd:permission denied
Q: How do I manipulate file handles?

A: Previous examples have been involved, we can directly invoke "read" through the file handle, "write" function, their function corresponds to the function of their own io.*() form, because io.*() the form of the function actually called is io.input():*() ,

Localf =io. Open ("File","w+")--[[Its function is equivalent to "io.input (" file "); Io.read ()". Because "Io.read ()" Actually calls "Io.input (): Read ()". ]]F:read () forLinchF:lines () Do     --"file:lines ()" differs from "io.lines ()" and does not close the file handle at the end of the loop.     --Do somethingEndF:write ("Something") F:flush ()--Forces the write cache to be saved to a file. --[[file:setvbuf (mode [, size]) sets the buffering mode of the data written to the file. "Mode" can be set to the following value: "No": not buffered.     The write data is stored directly in the file. "Full": Fully buffered.     The data is written to a file only when the cache is full or when flush () is explicitly called to the file. "Line": Row buffer.     Writes data to a file when a newline is encountered (for some special files, such as terminal devices, before any input is encountered). For the latter two modes, "size" specifies the size of the buffer in bytes. ]]--[[File:seek ([whence [, offset]]) According to"whence"Specifies the mode to offset the current read position of the file"offset"A byte."whence"The modes you can specify are as follows:"Set": Navigates the file's current read location to the beginning of the file."cur": Navigates the current read position of the file to the current location."End": Navigates the file's current read location to the end of the file."whence"Default is"cur";"offset"Default is0。     The function returns the offset of the file's current read position from the beginning of the file. This function does not have a corresponding"Io.seek ()"。 ]]--Gets the size of the file without changing the file read location.  function fsize(file)     LocalCurrent = File:seek ()--Get current position    LocalSize = File:seek ("End")--Get file sizeFile:seek ("Set", current)--Restore position    returnSizeEndF:close ()
Q: How do I export the contents of a file according to the hexadecimal editor's style?

A:

--Content in the "A.lua" file:LocalF = assert (IO.Open(arg[1],"R"))Localblock =Ten    --Convert 10 characters at a time, as a single line display.  while true  Do    Local bytes= f:Read(block)if  not bytes  ThenBreakEnd     forBinch string. Gmatch (bytes,".") Do    --matches any character.         -Converts a character to a 16-binary form. Io.Write(string.format("%02x",string.byte(b)))End    --[[the spaces between hexadecimal and normal characters ("+1" is the space).          "%02x"The model is just3characters, so if the last line is insufficientTencharacters, each of which is not enough character position to use3A space instead. ]] IO.Write(string. Rep ("   ", Block-string.Len(bytes) +1))--control characters are converted to "." Output. Io.Write(string. Gsub (bytes,"%c","."),"\ n")End--Take the script itself as the input file. --[[Result:> Luaa. Luaa. Lua6C6F the  A 6C -  the  - 3D -    Localf = A  the  the  $  the  About  -  the 6F2E assert (IO.6F -  $ 6E -  A  the  the 5B to    Open(arg[1... -  About  $  the 2C -  A  -  the  AYtes,"%c"     2C -  A 2E A  in 2C -  A 5C"."),"6E 0A 6E 0A n").End.]]
Additional:

1, when the file is empty, or the current read location of the file at the end of the file, the file:read() io.read() same behavior. file:read("a")will return an empty string, file:read("l") and Io.read ("*number") will return nil.
2.

local f = io.open("file""r")...    -- 执行若干次"f:read()"。print(f:seek())    -- 打印文件当前的读取位置。print(f:seek("end"0))    -- 打印文件大小。

3, I/O library also provides 3 predefined standard file handles, io.stdin io.stdout and io.stderr . You can use them to read or write directly to standard input, standard output, and standard error output.

print(io.stdin:read())    -- 输入什么,打印什么。print(io.stdout:write("123"))    -- 123print(io.stderr:write("123"))    -- 123

4. In Lua, it is faster to read a file as a whole than a row-by-line read. But sometimes we face huge files that are not suitable for our one-time reads (such as 10M or 100M files), and if you want to achieve the best performance when reading such files, you can read them in a "chunk" size (for example, 8KB). To prevent a row in the original file from being truncated, io.read() add one more parameter to the *l

--[[content in "file" files: line1 ABC line2 line3 def]]--contents of "A.lua" file:LocalBUFSIZE =2^ -    --8KLocalf =io. Input (arg[1])--Open input fileLocalCC, LC, WC =0,0,0    --Char, line, and word counts while true  Do    --first read the size of a "chunk". To prevent a row from being truncated, the rest of the bank is read out.     LocalLines, rest = F:read (BUFSIZE,"*l")if  notLines Then  Break End    ifRest Thenlines = lines. RestEnd    --stitch The truncated line up again. CC = CC +string. Len (lines)--The total number of characters that are included.     Local_, T =string. Gsub (lines,"%s+","")-The total number of words. WC = WC + t _, T =string. Gsub (lines,"\ n","\ n")--The total number of rows included. LC = LC + TEndPrint(LC, WC, CC)--The result of printing is the same as the "WC" command. --[[Result: > Lua A.lua file 3 5 > WC file 3 5 [file]]

5. In Unix-like operating systems, there is no difference between text-mode files and binary-mode files. However, the Windows operating system can be different, requiring a specific flag to correctly open the binary file. So if your program needs to consider cross-platform, it's a good idea to specify the "B" flag when opening a binary file.

--[[ 一个比较实用的例子是转换Windows中的换行符"\r\n"到Unix中的换行符"\n"。     我们不使用标准输入和标准输出,因为他们是以文本模式读取和写出数据的,     取而代之的是使用参数指定输入输出文件。]]localassert(io.open(arg[1"rb"))localassert(io.open(arg[2"wb"))local data = inp:read("*a"string"\r\n""\n")out:write(data)assert(out:close())

Quick Master Lua 5.3--I/O Library (2)

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.