Lua - Checking if File Exists



We can check if file is existing 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 present or not.

Example - Checking if file exists

We're making a check on example.txt which is present in the current directory where lua program is running.

main.lua

-- check if file exists
function exists(filename)

   local isPresent = true
   -- Opens a file
   f = io.open(filename)

   -- if file is not present, f will be nil
   if not f then
      isPresent = false
   else
      - close the file  
      f:close()
   end

   -- return status
   return isPresent
end

-- check if file is present
if exists("example.txt") then
   print("example.txt exists.")
else
   print("example.txt does not exist.")
end

Output

When we run the above program, we will get the following output−

example.txt exists.

Example - Checking if file is not existing

We're making a check on example1.txt which is not present in the current directory where lua program is running.

main.lua

-- check if file exists
function exists(filename)

   local isPresent = true
   -- Opens a file
   f = io.open(filename)

   -- if file is not present, f will be nil
   if not f then
      isPresent = false
   else
      - close the file  
      f:close()
   end

   -- return status
   return isPresent
end

-- check if file is not present
if not exists("example1.txt") then
   print("example1.txt does not exist.")
else
   print("example1.txt exists.")
end

Output

When we run the above program, we will get the following output−

example1.txt does not exist.
Advertisements