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

fs api help

Started by asnarr204, 06 March 2015 - 01:46 PM
asnarr204 #1
Posted 06 March 2015 - 02:46 PM
I am still a bit new at computercraft and wanted to experiment with creating files. I wanted to start out by creating a program, that when run, would check the first line of a file for a number, then add one to that number and replace the number in the file. Can someone show me how to do this, I have been having trouble replacing the number. Here is what I have:

local r = fs.open("testFile","r")
oldNum = r.readLine(1)
oldNum = tonumber(oldNum)
print("Old: "..oldNum)
newNum = oldNum + 1
print("New: "..newNum)
fs.delete("testFile")
local w = fs.open("testFile","a")
w.writeLine(newNum)
local h = fs.open("testFile","r")
read = h.readLine(1)
if not read == nil then
	print("done")
end

For some reason the new number is never written into the file. How do I fix this?
Edited on 06 March 2015 - 01:53 PM
GopherAtl #2
Posted 06 March 2015 - 02:57 PM
you have to close the file after each use; r, where you opened it to read, you must call r.close() before you'll be able to open the file again for writing. I'd expect the fs.delete to fail, too actually? but being sure to close your handles after you're done reading or writing them is important.
asnarr204 #3
Posted 06 March 2015 - 03:02 PM
OK thank you so much it works now. :lol:/>
MKlegoman357 #4
Posted 06 March 2015 - 03:07 PM
Also, for writing you are opening a file in append mode which doesn't overwrite the data on the file but append to it. You should be using write ("w") mode instead, there's no need to delete the file. Also, file.readLine returns the next line in the file so passing it 1 will do nothing. And lastly, "not read == nil" is the same as "(not read) == nil". I think you meant "read ~= nil".
asnarr204 #5
Posted 06 March 2015 - 03:09 PM
If I don't delete the file how do I get rid of the old number in it?
MKlegoman357 #6
Posted 06 March 2015 - 03:10 PM
Opening the file in "w" (write) mode will automatically delete all the previous data.
asnarr204 #7
Posted 06 March 2015 - 03:11 PM
Ok thank you