139 posts
Posted 21 October 2012 - 06:03 PM
I just earned how to use fs api and tables and when I tried to use the following program to read data so far and then add something to it I got
write;9; attempt to index ? (a nil value)
if fs.exists("data1") == false then
print("data1 not found")
sleep(2)
os.reboot()
end
write("data to be added: ")
x = read()
fs.open("data1","a")
datread = data1.readAll()
data1.write(x)
datread = data1.readAll()
print(datread)
how do i fix this?
8543 posts
Posted 21 October 2012 - 06:17 PM
You need to use the file handle. You're opening data1, but not keeping the file handle it returns, then attempting to use data1 as the file handle. Try changing the fs.open to have data1 = in front of it.
Also, you can't read from the file in append mode anyway. Check out the tutorials section to learn about basic input and output operations.
2088 posts
Location
South Africa
Posted 21 October 2012 - 07:58 PM
if not fs.exists("data1") then
print("data1 not found")
sleep(2)
os.reboot()
end
file = fs.open("data1","r")
fileReadBefore = file.readAll()
file.close() -- You have to close the file so you can open it again to append 'x' into the file
write("data to be added: ")
x = read()
file = fs.open("data1","a") -- 'a' for append to write 'x' into the file
file.write(x)
file.close()
file = fs.open("data1","r")
fileReadAfter = data1.readAll()
file.close()
print(fileReadBefore)
print(fileReadAfter)
8543 posts
Posted 21 October 2012 - 08:23 PM
The writing should probably be done in the write mode, not the append mode.
318 posts
Location
Somewhere on the planet called earth
Posted 21 October 2012 - 08:24 PM
Appended mode starts writing below the last line.
w mode replaces the whole file with what you write to it
2088 posts
Location
South Africa
Posted 21 October 2012 - 08:40 PM
The writing should probably be done in the write mode, not the append mode.
I assumed he would want to keep the other text
2005 posts
Posted 21 October 2012 - 09:38 PM
Hmm…for a data file that is keeping a log of some kind, probably he would. But most other cases, probably not. This does look like it might be for accessing some kind of log, though.