system.pathForFile() ... is the example in the API docs wrong?

The example for use in the API docs is:

local path = system.pathForFile( "data.txt", system.DocumentsDirectory ) local fhd = io.open( path ) -- Determine if file exists if fhd then print( "File exists" ) fhd:close() else print( "File does not exist!" ) end

If data.txt doesn’t exist, the path variable will be equal to nil. Using it as an argument to io.open will generate a runtime error “bad argument #1 to ‘open’ (string expected, got nil)”. That means the next few lines, to determine if the file exists, are never reached if the file doesn’t exists.

I thought the below would be the way to test if the file exists?

local path = system.pathForFile( "data.txt", system.DocumentsDirectory ) if path ~= nil then local fhd = io.open( path ) print( "File exists" ) fhd:close() else print( "File does not exist!" ) end

Not sure about the docs, but this code will work (and add ‘exists()’ to io lib):

function io.exists( fileName, base ) base = base or system.DocumentsDirectory if( base ) then fileName = system.pathForFile( fileName, base ) end if not fileName then return false end local f=io.open(fileName,"r") if (f == nil) then return false end io.close(f) return true end

Not sure about the docs, but this code will work (and add ‘exists()’ to io lib):

function io.exists( fileName, base ) base = base or system.DocumentsDirectory if( base ) then fileName = system.pathForFile( fileName, base ) end if not fileName then return false end local f=io.open(fileName,"r") if (f == nil) then return false end io.close(f) return true end