Jump to content




help with reading from a file


  • You cannot reply to this topic
6 replies to this topic

#1 tom2018

  • Members
  • 135 posts

Posted 21 October 2012 - 05: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)

Quote



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?

#2 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 21 October 2012 - 05: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.

#3 remiX

  • Members
  • 2,076 posts
  • LocationSouth Africa

Posted 21 October 2012 - 06: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)


#4 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 21 October 2012 - 07:23 PM

The writing should probably be done in the write mode, not the append mode.

#5 sjele

  • Members
  • 334 posts
  • LocationSomewhere on the planet called earth

Posted 21 October 2012 - 07:24 PM

Appended mode starts writing below the last line.
w mode replaces the whole file with what you write to it

#6 remiX

  • Members
  • 2,076 posts
  • LocationSouth Africa

Posted 21 October 2012 - 07:40 PM

View PostLyqyd, on 21 October 2012 - 07:23 PM, said:

The writing should probably be done in the write mode, not the append mode.

I assumed he would want to keep the other text

#7 ChunLing

  • Members
  • 2,027 posts

Posted 21 October 2012 - 08: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.





2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users