I/O 库为文件操作提供两种模式。简单模式(simple model)拥有一个当前输入文件和一个当前输出文件,并且提供针对这些文件相关的操作。完全模式(complete model)使用外部的文件句柄来实现。
- "*all" 读取整个文件
- "*line" 读取下一行
- "*number" 从串中转换出一个数值
- num 读取 num 个字符到串
简单模式:
- io.write("hello", "Lua"); io.write("Hi", "\n") --io.write
- io.write(string.format("sin (3) = %.4f\n", math.sin(3)))
-
- local line = io.read() --io.read
- local block = io.read(size)
完全模式:类似C语言的文件流FILE*
- io.open(filename, mode) --打开文件,mode: r读,w写,a追加, b二进制
- local f = assert(io.open(filename, mode)) --查错
- -------------------------------------------------------------------
- local f = assert(io.open(filename, "r")) --打开文件读
- local t = f:read("*all") --读取整个文件
- f:close() --关闭文件
- --------------------------------------------------------------以固定大小读取文件
- local BUFSIZE = 2^13 -- 8K
- local f = io.input(arg[1]) -- open input file
- local cc, lc, wc = 0, 0, 0 -- char, line, and word counts
- while true do
- local lines, rest = f:read(BUFSIZE, "*line")
- if not lines then break end
- if rest then lines = lines .. rest .. '\n' end
- cc = cc + string.len(lines)
- -- count words in the chunk
- local _,t = string.gsub(lines, "%S+", "")
- wc = wc + t
- -- count newlines in the chunk
- _,t = string.gsub(lines, "\n", "\n")
- lc = lc + t
- end
- print(lc, wc, cc)
- ------------------------------------------------------
- 二进制文件
- local inp = assert(io.open(arg[1], "rb")) --读二进制
- local out = assert(io.open(arg[2], "wb")) --写二进制
-
- local data = inp:read("*all")
- data = string.gsub(data, "\r\n", "\n")
-
- out:write(data)
- assert(out:close())
- -----------------------------------------文件大小
- function fsize (file)
- local current = file:seek() -- get current position
- local size = file:seek("end") -- get file size
- file:seek("set", current) -- restore position
- return size
- end