首页 > 编程知识 正文

lua写入文件,openresty从入门到精通

时间:2023-05-06 00:50:20 阅读:28233 作者:1084

Talk is cheap. Show me the code。

lua读写操作很麻烦,所以暂时封装了。

阅读文件:

-阅读文件

-参数:要读取的文件的路径

-返回值:读取的内容、读取错误。

-如果未加载内容,则第一个参数为nil,否则第二个参数为nil

localfunctionread _ file (file _ name )

if not file_name then

return nil,' missing file_name '

结束

localfile=io.open(file_name,' r ' )。

if not file then

返回编号,' can' top enfile' ' . file _ name . '"

结束

local content=file : read (' * all ' ) )。

文件: close ()

返回内容,nil

结束

写文件:

-写文件

-参数:要写入的文件路径、写入内容

-返回值:写入结果

-如果内容未写入,则返回错误内容;如果内容未写入,则返回nil

本地功能write _ file (file _ name,content ) )。

if not file_name then

return nil,' missing file_name '

结束

内容=content or ' '

localfile=io.open(file_name,' a ' ) )

if not file then

return ' can' top enfile' ' . file _ name . '' '

结束

文件:写入(内容)

文件: close ()

返回Nil

结束

实战演习:

-读取和写入文件演示,写入和读取当前时间

ngx.say (' write_fileresultis : ',write _ file ) (/tmp/nowtime.log ),ngx.now ) )

ngx.say (result _ fileresultis : (,read_file ) )/tmp/nowtime.log )

-你可以这么做

本地内容,err=read_file(/tmp/tttt.log ) )。

if not content then

是NGX.say(err )

else

NGX.Say(Content ) ) ) ) ) ) ) ) )。

结束

-本机中不存在文件tttt.log,因此显示如下。

-- can't open file '/tmp/tttt.log '

截图:

image.png

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。