object:read()

Type Function
Object File
Library io.*
Return value String, Number, or nil
Revision Release 2024.3703
Keywords read, files
See also io.open()
Reading and Writing Files

Overview

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.

Syntax

File:read( [fmt1] [, fmt2] [, ...] )
fmt1, fmt2, ... (optional)

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.
  • Number — Reads up to this number of characters, returning nil on end of file. If this number is 0, it reads nothing and returns an empty string, or nil on end of file.

Example

-- 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