Load String From File

This loads the contents of a text file into a string variable.

See counterpart Code Snippet Save String To File.

Requires: None

Code

-- Open File and return Handle --
function OpenFile(strFileName,strMode)
	local fileHandle, strError = io.open(strFileName,strMode)
	if not fileHandle then
		error("\n Unable to open file in \""..strMode.."\" mode. \n "..strFileName.." \n "..tostring(strError).." \n")
	end
	return fileHandle
end -- function OpenFile
 
-- Load string from file --
function StrLoadFromFile(strFileName)
	local fileHandle = OpenFile(strFileName,"r")
	local strString = fileHandle:read("*all")
	assert(fileHandle:close())
	return strString
end -- function StrLoadFromFile

 

Alternate Version

function strLoadFromFile(strFileName)
    -- Load string from file --
    -- Returns String from file, or a nil and an error value
    local fileHandle, err = io.open(strFileName,'r')
    if fileHandle then
        local strString = fileHandle:read("*all")
        fileHandle:close()
        return strString
    else
        return nil, err
    end
end 

 

Usage

local str,err = strLoadFromFile('d:\\temp\\html test.lua')
if err then
    print('Error:'..err)
else
    print(str)
end