readfile

function readfile( filename ) --> str, err

Description

Reads an entire file(filename) into a string(str). If an error occurse returns the function nil and an error message.

Parameters

filename

Path to the file that should be read.

Return Values

str

The file as string or nil if an error occurse.

err

A message if an error occurse otherwise nil.

Code

--ZFUNC-readfile-v1
local function readfile( filename ) --> str, err
   local f, err = io.open( filename, "r" )
   if err then return nil, err end

   local str, err = f:read( "*a" )
   if err then return nil, err end

   local res, err = f:close()
   if err then return nil, err end

   return str
end

return readfile

Examples

local t = require( "taptest" )
local readfile = require( "readfile" )

f = io.open( "ReadFileXmpl.txt", "w" )
f:write( "a ", "long ", "text\n", "is ", 1337 )
f:close()

str, err = readfile( "ReadFileXmpl.txt" )
t( str, "a long text\nis 1337" )
t( err, nil )

os.remove( "ReadFileXmpl.txt" )

t()