美文网首页Lua
Openresty+Lua 读写文件

Openresty+Lua 读写文件

作者: 8e744d4a988c | 来源:发表于2020-03-25 22:13 被阅读0次

Talk is cheap. Show me the code.

因为 lua 写读写操作比较麻烦,所以大致封装了一下。

读文件:

-- 读文件
-- 参数:需要读取的文件路径
-- 返回值:读出的内容,读取错误。
-- 如果没有读出内容,第一个参数为 nil,否则第二个参数为 nil
local function read_file(file_name)
    if not file_name then
        return nil, "missing file_name"
    end
    local file = io.open(file_name,'r')
    if not file then
        return nil, "can\'t open file \"" .. file_name .. "\""
    end
    local content = file:read('*all')
    file:close()
    return content, nil
end

写文件:

-- 写文件
-- 参数:需要写入的文件路径,写入内容
-- 返回值:写入结果
-- 如果没有写入内容,返回错误内容,否则返回 nil
local function write_file(file_name, content)
    if not file_name then
        return nil, "missing file_name"
    end
    content = content or ''
    local file = io.open(file_name, "a")
    if not file then
        return "can\'t open file \"" .. file_name .. "\""
    end
    file:write(content)
    file:close()
    return nil
end

实战演练:

-- 读写文件演示,写入当前时间,再读取出来
ngx.say("write_file result is: ", write_file("/tmp/nowtime.log", ngx.now()))
ngx.say("result_file result is: ", read_file("/tmp/nowtime.log"))
-- 也可以这样
local content, err =  read_file("/tmp/tttt.log")
if not content then
    ngx.say(err)
else
    ngx.say(content)
end
-- 本机不存在文件 tttt.log,所以显示:
-- can't open file "/tmp/tttt.log"

截图:


image.png

相关文章

  • Openresty+Lua 读写文件

    Talk is cheap. Show me the code. 因为 lua 写读写操作比较麻烦,所以大致封装了...

  • C语言读写文件

    C语言文件读写### 标准文件读写 非标准文件读写 标准文件读写 头文件 include 打开文件 函数原型:FI...

  • 跟我一起学Python(八)

    一、IO编程 读写文件是最常见的IO操作,Python内置了读写文件的函数。文件读写的原理:在磁盘上读写文件的功能...

  • Python 学习笔记6 2018-04-13

    文件操作: 1,文件的读写操作 2,文件的各种系统操作 3,存储对象 1,文件的读写操作 读写数据: ...

  • 用Python实现磁盘IO操作全攻略,让数据流动起来!

    01 文件读写 1. 打开文件 读写文件是最常见的IO操作。Python内置了读写文件的函数,方便了文件的IO操作...

  • 2018-04-05

    文件与文件路径读写文件用shelve模块保存变量 1 python 读写文件 1.1 文件与文件路径 window...

  • 文件操作导航

    文件打开与关闭文件读写文件的定位读写文件的重命名、删除文件夹的相关操作

  • R数据读写

    csv文件读写 txt文件读写 读取excel文件 转成csv文件读取(逗号分隔) 专程prn文件读取(空格分隔)...

  • python学习笔记03

    文件处理 读写文件是最常见的IO操作。Python内置了读写文件的函数,用法和C是兼容的。 读写文件前,我们先必须...

  • python 文件操作

    读写文件通常包含以下操作: 打开文件。获取文件对象 读写文件、对文件内容进行操作。 关闭文件。使用文件对象关闭文件...

网友评论

    本文标题:Openresty+Lua 读写文件

    本文链接:https://www.haomeiwen.com/subject/tpkfuhtx.html