lua内置函数读写文件

来源:互联网 发布:c语言编程好的小程序 编辑:程序博客网 时间:2024/06/06 10:03
用lua内置函数读写文件--io.open(文件名,操作方式)--操作方式有"w" 写模式 "r"读模式 "a"追加模式function writefile_test()myfile=io.open("lisaisai.txt","w")--myfile相当于文件句柄 文件指针if myfile==nil thenprint("创建文件出错")elsemyfile: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() --关闭文件endfunction readfile_test2()myfile=io.open("lisaisai.txt","r")--myfile相当于文件句柄 文件指针if myfile==nil thenprint("创建文件出错")elsewhile true doline=myfile:read("*l") --读到文件末尾返回一个空print(line)if line==nil thenbreakendendend --end for myfile:close()endfunction readfile_test1()myfile=io.open("lisaisai.txt","r")--myfile相当于文件句柄 文件指针if myfile==nil thenprint("创建文件出错")elsefor i in myfile:lines() do --功能:返回一个迭代函数,每次调用将获得文件中的一行内容,当到文件尾时,将返回nil,但不关闭文件print(i)endend --end for myfile:close()endwritefile_test()readfile_test1()--readfile_test2()

0 0
原创粉丝点击