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

[Closed][Lua][Question] How to make, write in and read from a file

Started by IceCrasher, 25 March 2013 - 01:44 AM
IceCrasher #1
Posted 25 March 2013 - 02:44 AM
Hi guys i really need your help.

I tried finding a good explanation how I could just wirte a litte "1" or "100" or something in a file whit the fs.*** api, but i failed. So please can you help me with a litte example out, just creating, overwrite and read from a file whit a variable.

Thank you for reading and may supporting :)/>
SuicidalSTDz #2
Posted 25 March 2013 - 02:51 AM

local handle = fs.open(yourFile,mode) --"w" will write to the file and "r" will read from the file
handle.writeLine(yourTextHere) --Must be a string
handle.close() --You must always close the file you are manipulating
The wiki also has an excellent documentation of all the functions that the fs library reveals

Here is what it should look like:

local file = fs.open("test","w") --Using write will automatically wipe the file of its contents. Append("a") will not, it will insert the text at the end of a file
file.writeLine("1")
file.close()

Reading the file:

local file = fs.open("text","r") --Open the file in read mode
local data = file.readAll() OR file.readLine() depending on what you need. In this case it will be readLine
file.close()
print(data)
->1
Engineer #3
Posted 25 March 2013 - 03:06 AM
A very good tutorial: http://www.computercraft.info/forums2/index.php?/topic/10654-storing-variables-in-a-file/
IceCrasher #4
Posted 25 March 2013 - 03:06 AM
@SuicidaISTDz
Thank you sooooo much you're the man, really thank you a lot!!! You saved some hours of work :)/>

@Engineer
Thank you too. If you belive or not, i read your tutorial some days ago, but i didn't get it with this assert and all those things :/ It was to advanced for me…
SuicidalSTDz #5
Posted 25 March 2013 - 03:10 AM
Lol, LBHacker goes all out, doesnt he :P/>