Lua - Deleting Files



Lua provides os table which we can utilize to perform operating system specific tasks like renaming a file, removing a file. We can use os.remove() function to removing a file.−

Syntax - os.remove() method

result, message = os.rename (filename)

Where−

  • filename− file name to be removed.

This method removes the file and returns result as true if operation is successful otherwise nil. message represents the error message if any error occurred while removing the file like file is not present or file cannot be deleted being in use by some application and so.

Example - Deleting an existing file

Let us first check the failure case. We're trying to delete an existing file where lua program is not having permission to delete.

main.lua

-- file to be deleted
local fileName = "example1.txt"

result, message = os.remove(fileName)

-- if file is removed
if result then
   print("File deleted successfully.")
else
   print("File deletion failed.", message)
end 

Output

When the above code is built and executed, it produces the following result −

File deletion failed.	example1.txt: Permission denied

Example - Deleting a New file

Let's us now create a temporary file in current directory and delete it using os.remove() function.

main.lua

-- write a file content
function writeFile()
   -- Opens a file in write mode,
   -- create file if not present
   -- overwrite content of file if present
   f = io.open("example.txt","w")
   -- write the contents
   f:write("Welcome to tutorialspoint.com", "\n")
   f:write("Simply Easy Learning", "\n")
   -- close the file handle
   f:close()
end

-- write the file
writeFile()

print("Content written to the file successfully.")

-- file to be deleted
local fileName = "example.txt"

result, message = os.remove(fileName)

-- if file is removed
if result then
   print("File deleted successfully.")
else
   print("File deletion failed.", message)
end

Output

When the above code is built and executed, it produces the following result −

Content written to the file successfully.
File deleted successfully.
Advertisements