Using files in LuaRT
Tags: lua, windows, tutorial
Published: 2021-05-27 06:52:57

[LuaRT](https://www.luart.org) is a comprehensive Windows framework to develop in Lua with a specific runtime library. In the Lua standard library, input / output functionalities are gathered within the io module. In LuaRT, they are grouped together within the [sys](https://www.luart.org/doc/sys/index.html) module, and more particularly the [File](https://www.luart.org/doc/sys/file.html) object.

##Using the File object in LuaRT
The manipulation of files in LuaRT is facilitated by the use of **File** objects: creation of files, opening, closing, moving, copying, deleting ...

####Creating a File value
At this point, it's important to understand that a **File** object represents an abstraction of a file that may *or may not* physically exist. For example, when creating a new file, only the call to the **File:open()** method will physically create the file on the computer's storage:

```lua
local newfile = sys.File("hello.txt") -- newfile holds a File value
print(newfile.exists) -- outputs false
newfile:open("write") -- creates the file physically on the disk 
newfile:close()       -- closes the opened File
print(newfile.exists) -- now outputs true
```

####File operations
A **File** object can be used to perform file operations:

```lua
local file = sys.File("test.txt") 
file:copy("test_copy.txt")   -- copies file
file:move("C:\")             -- moves file
file:remove()                -- deletes the file
```

####Opening and closing a File
A file can be opened to read or write its content. This is done by calling the **File:open()** method. By default, the file is open in "read" mode. The file encoding can be specified as a second argument or detected using Byte Mark Order :

```lua
local file = File("test.bin")
file:open()   -- opens the file "test.bin" in read mode (encoding is autodetected)
file:close()                   -- closes the file
file:open("write", "binary")   -- open the file in write mode (erasing its previous content), using "binary" encoding(ie raw binary)
```

> Do not forget to close a file after the transaction on this one ended. This is done automatically when the **File** object is garbage collected, but that cannot be predicted.

####Reading and writing Files
Once the **File** object has been created, and the **File:open()** method called, you can write or read on the **File** (depending on the mode used in the call). These methods return Buffer objects in binary mode (containing in memory binary data) or strings in UTF8 or UNICODE mode.

#####Reading file content
There are two methods for reading the content of a file: **File:read()** and **File:readln()**

```lua
local file = File("README.TXT"):open()  -- opens the File for reading
print(file:read())  -- reads and prints all the file content 
```

The **File:read()** method reads a number of characters (when using UTF8 or UNICODE mode) or bytes (in binary mode) specified as argument, or all the content of the file if no argument is provided.

The **File:readln()** method reads a line (until end of line characters "\r\n" or "\n" are encountered).

#####Writing to files
There are two methods for writing data to a file: **File:write()** and **File:writeln()**

Each method take one argument, converted to a string to be written to the file. In binary mode, **Buffer** objects can be used.

**File:writeln()** writes a line to the file, appending "\r\n" (corresponding to the End Of Line marker on Windows).

####File position

The **File.position** property get or set the current file position, as a number. File position always starts at 1 (as for all indexed/positioned values in Lua). 
File position interpretation depends on the file encoding.
In "binary" encoding : the position is expressed in bytes.
In "utf8" or "unicode" encoding : the position is expressed in characters.
The **File.eof** property checks if the end of the file have been reached.

####File timestamps
The **File.accessed**, **File.modified** and **File.created** permits to set or get timestamps using a **Datetime** object (in LuaRT, **Datetime** objects represent a moment, a combination of a date and a time).

####File attributes
The **File.hidden**, **File.temporary** and **File.readonly** permits to set or get the corresponding attributes.

####File path and names
The **File.fullpath**, **File.filename**, **File.extension**, **File.path** permits to get access to the different parts of a filename.

As you can see, File objects provide easy access to all of the functionality related to creating, reading, writing and manipulating files in LuaRT. These features go beyond the capabilities offered by the standard Lua library.