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

Reading every line in a file and returning it

Started by kotorone1, 08 September 2012 - 05:48 PM
kotorone1 #1
Posted 08 September 2012 - 07:48 PM
Hello,

I am trying to make a program that opens a file, reads a line in the file, returns each line as a string, and then adds that string to a table. and returns every line as a seperate string, then saves those values to a table. I do not want to use file.readAll(), because i want each line stored as a seperate value on a table. Any help would be appreciated.

here is what i have so far on my current re-write of this program


--Declare Variable
local loc = "/UID"
--declare funtions
function readFile()
if fs.exists(loc) then
  local tFile = io.open(loc,"r")
  if tFile then
   for line in tFile:lines() do
	print(tFile.readLine())
   end
  end
end
end
--Run fucntions
readFile()

I really only need help figuring out how to read the file, the rest I can do myself.

Thanks,
~Matt
sjele #2
Posted 08 September 2012 - 08:15 PM

file = /VID
line = {}

function readAllLines()
if fs.exists(file) then
open = fs.open(file, "r")
num = 1
repeat
line[num] = open.readLine()
num = num + 1
until line[num] == ""
open.close()
end
end

I belive this works
WildCard65 #3
Posted 08 September 2012 - 09:05 PM
or use the io api.
kotorone1 #4
Posted 09 September 2012 - 12:08 AM
Having some problems with this.

line[num] = open.readLine()
Does not work. I have changed the loop to a "while" loop, but no matter how i code the loop, it always returns a "too long wihout yielding error". So I added a "sleep(0)" to the loop, and it fixed the yielding error, but it results in the program doing nothing
Kingdaro #5
Posted 09 September 2012 - 01:03 AM
You can use :gmatch().


function readFile()
  local file = fs.open('your/file/path')
  local data = fs.readAll()
  file.close()
  
  local t = {}
  for v in data:gmatch('(.-)n') do
    table.insert(t,v)
  end
  return t
end
This returns a table of all of the lines.
ltstingray #6
Posted 09 September 2012 - 04:22 AM
I haven't had a chance to test this but in theory, it should work.

Spoiler

These code tags love to mess up my formatting :/ 

Instead of above see:
http://pastebin.com/r4mi76LY
Lyqyd #7
Posted 09 September 2012 - 05:10 AM
You guys are really doing this the hard way.


local fileTable = {}
file = io.open("fileName", "r")
if file then
    for line in file:lines() do
        table.insert(fileTable, line)
    end
end