object:read()

类型 函数
对象 文件
io.*
返回值 字符串数字nil
修订 发行版 2024.3703
关键字 读、文件
另请参阅 io.open()
读取和写入文件

概览

根据指定格式读取文件,该格式指定要读取的内容。对于每种格式,该函数均返回一个具有所读字符的字符串数字,或者若无法使用指定格式读取数据,则返回nil。在未调用格式的情况下,它将使用默认格式读取下一整行。

语法

File:read( [fmt1] [, fmt2] [, ...] )
fmt1, fmt2, … (可选)

字符串数字可用的格式为

  • "*l" — 读取下一行(跳过行尾),在文件结尾(EOF)处返回nil。这是默认格式。
  • "*n" — 读取数字;这是唯一返回数字而不是字符串的格式。
  • "*a" — 读取整个文件,从当前位置开始。在文件结尾处,它返回空字符串。
  • 数字 — 读取不超过此数量的字符,在文件结尾处返回 nil。如果此数字为 0,则它不会读取任何内容并返回一个空字符串,或者在文件结尾处返回 nil

示例

-- Path for the file to read
local path = system.pathForFile( "myfile.txt", system.DocumentsDirectory )

-- Open the file handle
local file, errorString = io.open( path, "r" )

if not file then
    -- Error occurred; output the cause
    print( "File error: " .. errorString )
else
    -- Read data from file
    local contents = file:read( "*a" )
    -- Output the file contents
    print( "Contents of " .. path .. "\n" .. contents )
    -- Close the file handle
    io.close( file )
end

file = nil