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

help with reading from a file

Started by tom2018, 21 October 2012 - 04:03 PM
tom2018 #1
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?
Lyqyd #2
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.
remiX #3
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)
Lyqyd #4
Posted 21 October 2012 - 08:23 PM
The writing should probably be done in the write mode, not the append mode.
sjele #5
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
remiX #6
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
ChunLing #7
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.