文件输入输出 |
|
nil
)可以避免在失败时静默继续。
-- Find the length of a file -- filename: file name -- returns -- len: length of file -- asserts on error function length_of_file(filename) local fh = assert(io.open(filename, "rb")) local len = assert(fh:seek("end")) fh:close() return len end -- Return true if file exists and is readable. function file_exists(path) local file = io.open(path, "rb") if file then file:close() end return file ~= nil end -- Guarded seek. -- Same as file:seek except throws string -- on error. -- Requires Lua 5.1. function seek(fh, ...) assert(fh:seek(...)) end -- Read an entire file. -- Use "a" in Lua 5.3; "*a" in Lua 5.1 and 5.2 function readall(filename) local fh = assert(io.open(filename, "rb")) local contents = assert(fh:read(_VERSION <= "Lua 5.2" and "*a" or "a")) fh:close() return contents end -- Write a string to a file. function write(filename, contents) local fh = assert(io.open(filename, "wb")) fh:write(contents) fh:flush() fh:close() end -- Read, process file contents, write. function modify(filename, modify_func) local contents = readall(filename) contents = modify_func(contents) write(filename, contents) end
以下示例来自 Lua 4,仅出于历史原因在此处包含。
-- Guarded readfrom (Lua4) -- [f]: file name -- Note: In Lua5 use io.input(). function readfrom(f) local h, err if f then h, err = %readfrom(f) else h, err = %readfrom() end affirm(h, "can't read from " .. (f or "stdin") .. ": " .. (err or "")) return h end -- Guarded writeto (Lua4) -- [f]: file name -- Note: In Lua5 use io.output(). function writeto(f) local h, err if f then h, err = %writeto(f) else h, err = %writeto() end affirm(h, "can't write to " .. (f or "stdout") .. ": " .. (err or "")) return h end -- Guarded dofile (Lua4) -- [f]: file name -- Note: In Lua5, dofile throws on error. function dofile(f) affirm(%dofile(f), "error while executing " .. f) end -- Guarded seek (Lua4) -- f: file handle -- w: whence to seek -- o: offset function seek(f, w, o) local ok, err if o then ok, err = %seek(f, w, o) elseif w then ok, err = %seek(f, w) else ok, err = %seek(f) end affirm(ok, "can't seek on " .. f .. ": " .. (err or "")) end -- Find the length of a file (Lua4) -- f: file name -- returns -- len: length of file function length_of_file(f) local h, len h = openfile(f, "r") len = seek(h, "end") closefile(h) return len end
--JayCarlson - 原版(Lua 4 版本)