Lua - Checking if File is Readable
It is always good to check if a file is readable before reading a file and then handle the situation gracefully. To check if file is readable or not, we can check the io.open() status.
Syntax - io.open()
f = io.open(filename, [mode])
Where−
filename− path of the file along with file name to be opened.
mode− optional flag like r for read, w for write, a for append and so on.
f represents the file handle returned by io.open() method. In case of successful open operation, f is not nil. Following examples show the use cases of checking a file is readable or not.
We're making a check on example.txt which is present in the current directory and is readable where lua program is running.
main.lua
-- check if file is readable
function readable(filename)
local isReadable = true
-- Opens a file in read mode
f = io.open(filename, "r")
-- if file is not readable, f will be nil
if not f then
isReadable = false
else
-- close the file
f:close()
end
-- return status
return isReadable
end
-- check if file is readable
if readable("example.txt") then
print("example.txt is readable.")
else
print("example.txt is not readable.")
end
Output
When we run the above program, we will get the following output−
example.txt is readable.
Example - Checking if file is not readable
We're making a check on system file which is not readable where lua program is running.
main.lua
-- check if file is readable
function readable(filename)
local isReadable = true
-- Opens a file in read mode
f = io.open(filename, "r")
-- if file is not readable, f will be nil
if not f then
isReadable = false
else
-- close the file
f:close()
end
-- return status
return isReadable
end
-- check if file is not readable
if not readable("C:\Windows\System32\dnsrslvr.dll") then
print("dnsrslvr.dll is not readable.")
else
print("dnsrslvr.dll is readable.")
end
Output
When we run the above program, we will get the following output−
example1.txt does not exist.