Lua - Reading 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.rename() function to rename a file.−

Syntax - os.rename() method

result, message = os.rename (source, target)

Where−

  • source− file name to be changed.

  • target− final name.

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

Example - Renaming an existing file

Let us now see how to rename a file. We're trying to rename an existing file.

main.lua

-- file to be renamed
local fileName = "example.txt"
local targetFileName = "example2.txt"

result, message = os.rename(fileName, targetFileName)

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

Output

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

File renamed successfully.

You can check in file system, where example1.txt is renamed to example2.txt.

Example - Renaming to an existing file

Let us now see a failure case where we're trying to rename to an existing file. We've created a new file example1.txt and are trying to rename it to an existing file example2.txt. os.rename() call will fail and error message will be printed.

main.lua

-- file to be renamed
local fileName = "example1.txt"
local targetFileName = "example2.txt"

result, message = os.rename(fileName, targetFileName)

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

Output

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

File renamed failed.	example1.txt: File exists
Advertisements