This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
houseofkraft's profile picture

Using the Filesystem in Lua Tutorial

Started by houseofkraft, 31 August 2016 - 04:13 PM
houseofkraft #1
Posted 31 August 2016 - 06:13 PM
So you might be asking yourself?

How do i use the file system in my program?

I know how i used to not be able to know the filesystem commands. But now i know and i want to share the same experience i know to you.

Filesystem Commands:

fs.open()fs.open will open a file so you can write/read to it, You will need to save it to a variable.

Syntax:
fs.open(<path>, <r/w>

Examples:

Writing:
myfile = fs.open("/test", "w") – Opens the file in write mode, will create the file if it does not exist
myfile.write("Testing") – Writes Testing to the file
myfile.close() – Closes the file so the system is no longer using the file

Reading:
myfile = fs.open("/test", "r") – Opens the file in read-only mode
line = myfile.readLine() – Stores the line in a variable
OR
code = myfile.readAll() – Reads all the code and stores it in a variable
myfile.close() – Closes the file so the system is no longer using the file

fs.exists()fs.exists will return true or false depending if the file exists, You need to have an if statement

Syntax:
fs.exists(<file>)

Example:
if fs.exists("/myFile") == true then
– Run's this code if file exists
print("myFile exists!")
else
print("myFile does not exist!")
end

fs.delete()Delete's a file
Syntax:
fs.delete(<name>)
Example:
fs.delete("/myFile")
fs.move()Move's a file from one location to another location
Syntax:
fs.move(source, destination)
Example:
fs.move("/myFile", "/Folder/myFile")
fs.copy()Copy's a file from one location to another location
Syntax:
fs.copy(source, destination)
Example:
fs.copy("/myFile", "/Folder/myFile")

There will be more filesystem tutorials later, but this is what I know right now. Thank You!
TheRockettek #2
Posted 31 August 2016 - 08:30 PM
Just a heards up theres 3 more modes for fs.open:

- a: Append move. Same as w (write mode) except instead of replacing e file, it will write from the end of the file.

- rb: Read (binary) mode: Same as read but returns the charactersas the codes of ids (eg: 126,46)

- rw: Write (binary) mode: Insert number, letter comes out (wrote to file) :D/>

Only if there was ab… Append (Binary)
NotSwedishFish #3
Posted 10 September 2016 - 12:53 AM
Some things to watch out for:

Just because your program works on your laptop's installation of Lua does not mean it will work in CC. For example, myfile:read("*a") will work on a normal computer, but not inside CC. It will also work in binary mode on a normal computer, but not in CC. Indeed, the API can be different, so make sure to check your FS operations.

None of the + file modes in the reference implementation of Lua will work.
Edited on 09 September 2016 - 10:54 PM