官方参考文档:http://www.lua.org/manual/5.1/
0.读写种类
r 读取模式
w 写入模式(覆盖现有内容)
a 附加模式(附加在现有内容之后)
b 二进制模式
r+ 读取更新模式(现有数据保留)
w+ 写入更新模式(现有数据擦除)
a+ 附加更新模式(现有数据保留,只在文件末尾附加)
1.一些函数
assert(file); 找不到文件抛出异常
2.读写文件
path = "/Users/admin/Desktop/file.rtf"
function FileReadSave()
local file = io.open(path, "r");
assert(file);
local data = file:read("*a"); -- 读取所有内容
print(data)
for l in file:lines() do --一行一行读取
print(l)
end
file:close();
file = io.open(path, "w");
assert(file);
file:write("dataa的速度a11\n"); -- \n 一行一行写进去
file:write("dataaa11\n");
file:write("dataaa11\n");
file:write("dataaa11\n");
file:close();
end
3.读写 table
cha = {};
cha[1] =
{
basic =
{
Name = "农民",
cha_type = 1,
},
combat =
{
acquire = 600.00,
basic_def = 10,
},
};
function SaveTableContent(file, obj)
local szType = type(obj);
print(szType);
if szType == "number" then
file:write(obj);
elseif szType == "string" then
file:write(string.format("%q", obj));
elseif szType == "table" then --把table的内容格式化写入文件
file:write("{\n");
for i, v in pairs(obj) do
file:write("[");
SaveTableContent(file, i);
file:write("]=\n");
SaveTableContent(file, v);
file:write(", \n");
end
file:write("}\n");
else
error("can't serialize a "..szType);
end
end
function SaveTable()
local file = io.open(path, "w");
assert(file);
file:write("cha = {}\n");
file:write("cha[1] = \n");
SaveTableContent(file, cha[1]);
file:write("}\n");
file:close();
end
SaveTable();
--I/O库为文件操作提供2个里一个输入库和一个输出库io.read() --io.write() 该函数将所有参数按照顺序写到当前输出文件中 FILE_NAME = 'd:/2013-08-08.txt' FILE_NAME2 = 'd:/lua1.txt' function write() io.write('hello ', 'world') end --write() --io.read() 读取当前文件的内容 "*all" "*line" "*number" number --[[for count = 1,math.huge do local line = io.read("*line") --如果不传参数,缺省值也是"*line" if line == nil then break end io.write(string.format("%6d ",count),line,"\n") end--]] --读取指定文件 function getFile(file_name) local f = assert(io.open(file_name, 'r')) local string = f:read("*all") f:close() return string end -- local lines,rest = f:read(BUFSIZE,"*line") function getFileLine(file_name) local BUFSIZE = 84012 local f = assert(io.open(file_name, 'r')) local lines,rest = f:read(BUFSIZE, "*line") f:close() return lines , rest end --字符串写入 function writeFile(file_name,string) local f = assert(io.open(file_name, 'w')) f:write(string) f:close() end writeFile(FILE_NAME2, getFile(FILE_NAME))
--控制台写入字符串到文件中 function writeFile2(file_name) local f = assert(io.open(file_name, 'w')) local string = io.read() f:write(string) f:close() end io.write() writeFile2(FILE_NAME2)
http://blog.youkuaiyun.com/renzhe20092584/article/details/27239613
http://blog.163.com/liwei1987821@126/blog/static/17266492820131011111035550/