Lua - Binary File Handling



In, by default all files are read/write in text mode. In unix there is no difference between binary and text file and all files are processed alike but in some systems like windows, binary files are to be handled differently. In lua, we can pass an additional flag b while reading/writing a file.

A simple binary file open operation uses the following statement.

file = io.open (filename [, mode])

The various file modes are listed in the following table.

Sr.No. Mode & Description
1

"rb"

Read-only binary mode and is the default mode where an existing file is opened.

2

"wb"

Write enabled binary mode that overwrites the existing file or creates a new file.

3

"ab"

Append binary mode that opens an existing file or creates a new file for appending.

4

"rb+"

Read and write binary mode for an existing file.

5

"wb+"

All existing data is removed if file exists or new file is created with read write permissions.

6

"ab+"

Append mode with read mode enabled that opens an existing file or creates a new file.

Example - Write Binary File Contents

Let us now see how to write a binary file.

main.lua

-- write a binary file
function writeFile()
   -- Opens a file in write mode
   f = io.open("length.lua","wb")
   -- set f as default input
   io.output(f)

   io.write("-- initialize a table","\n")
   io.write("table = { 1, 2, 3}","\n")

   io.write("-- print the length of the table as 3","\n")
   io.write("print(#table)","\n")

   -- close the file handle
   io.close(f)
   print("Content written to the file successfully.")
end

-- write the file
writeFile()

Output

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

Content written to the file successfully.

File Content

Above code create the file example.txt in current directory if not present otherwise overwrite the existing content. You can check the content of example.txt−

-- initialize a table
table = { 1, 2, 3}
-- print the length of the table as 3
print(#table)

Example - Reading a binary File

Let us now see how to read contents of a binary file.

main.lua

-- read a file content
function readFile()
   -- Opens a file in read mode, 
   f = io.open("length.lua","rb")
   -- set f as input    
   io.input(f)
   -- read all content of the File
   contents = io.read("*all")
   print(contents)   
   -- close the file handle
   f:close()
end

-- read the file 
readFile()

Output

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

-- initialize a table
table = { 1, 2, 3}
-- print the length of the table as 3
print(#table)
Advertisements