Type Function Object File Library io.* Return value String, Number, or nilRevision Release 2025.3721 Keywords read, files See also io.open() Reading and Writing Files
Reads a file, according to the given formats which specify what to read. For each format, the function returns a string or a number with the characters read, or nil if it cannot read data with the specified format. When called without formats, it uses a default format that reads the entire next line.
File:read( [fmt1] [, fmt2] [, ...] )
String or Number. The available formats are:
"*l" — Reads the next line (skipping the end of line), returning nil on end of file (EOF). This is the default format."*n" — Reads a number; this is the only format that returns a number instead of a string."*a" — Reads the whole file, starting at the current position. On end of file, it returns the empty string.nil on end of file. If this number is 0, it reads nothing and returns an empty string, or nil on end of file.-- 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