lua实现以字符串内容写入文件,成功返回 true,失败返回 false读取文件内容


// @function [parent=#io] writefile
// @param string path 文件完全路径
// @param string content 要写入的内容
// @param string mode 写入模式,默认值为 "w+b"
// @return boolean#boolean 



/*以字符串内容写入文件,成功返回 true,失败返回 false

"mode 写入模式" 参数决定 io.writefile() 如何写入内容,可用的值如下:

-   "w+" : 覆盖文件已有内容,如果文件不存在则创建新文件
-   "a+" : 追加内容到文件尾部,如果文件不存在则创建文件

此外,还可以在 "写入模式" 参数最后追加字符 "b" ,表示以二进制方式写入数据,这样可以避免内容写入不完整。

**Android 特别提示:** 在 Android 平台上,文件只能写入存储卡所在路径,assets 和 data 等目录都是无法写入的。

*/

function io.writefile(path, content, mode)
    mode = mode or "w+b"
    local file = io.open(path, mode)
    if file then
        if file:write(content) == nil then return false end
        io.close(file)
        return true
    else
        return false
    end
end

lua实现以字符串内容写入文件,成功返回 true,失败返回 false读取文件内容_第1张图片

// 读取文件内容,返回包含文件内容的字符串,如果失败返回 nil
// @function [parent=#io] readfile
// @param string path 文件完全路径
 @return string#string 

/*

读取文件内容,返回包含文件内容的字符串,如果失败返回 nil

io.readfile() 会一次性读取整个文件的内容,并返回一个字符串,因此该函数不适宜读取太大的文件。

*/

function io.readfile(path)
    local file = io.open(path, "r")
    if file then
        local content = file:read("*a")
        io.close(file)
        return content
    end
    return nil
end
lua实现以字符串内容写入文件,成功返回 true,失败返回 false读取文件内容_第2张图片

你可能感兴趣的:(Lua开发,Lua语言开发)