用lua内置函数读写文件
--io.open(文件名,操作方式)
--操作方式有"w" 写模式 "r"读模式 "a"追加模式
function writefile_test()
myfile=io.open("lisaisai.txt","w") --myfile相当于文件句柄 文件指针
if myfile==nil then
print("创建文件出错")
else
myfile:write(string.format("%s:%s\n","--文件创建时间",os.date()))
myfile:write(string.char(10)) --换行 也可以直接写入"\n"换行
myfile:write("--11111111111111\n")
myfile:write("--lua文件操作测试\n")
myfile:write("--lua文件操作测试\n")
end
myfile:close() --关闭文件
end
function readfile_test2()
myfile=io.open("lisaisai.txt","r") --myfile相当于文件句柄 文件指针
if myfile==nil then
print("创建文件出错")
else
while true do
line=myfile:read("*l") --读到文件末尾返回一个空
print(line)
if line==nil then
break
end
end
end --end for
myfile:close()
end
function readfile_test1()
myfile=io.open("lisaisai.txt","r") --myfile相当于文件句柄 文件指针
if myfile==nil then
print("创建文件出错")
else
for i in myfile:lines() do --功能:返回一个迭代函数,每次调用将获得文件中的一行内容,当到文件尾时,将返回nil,但不关闭文件
print(i)
end
end --end for
myfile:close()
end
writefile_test()
readfile_test1()
--readfile_test2()