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

how to read a file?

Started by cheekycharlie101, 24 November 2012 - 10:04 AM
cheekycharlie101 #1
Posted 24 November 2012 - 11:04 AM
ok, so i have been messing around with the file system api. but cant seem to do this. basically i want to code my own lock but the password is stored in another file.

so you enter in the password and it goes to another file and checks.
can anyone help me out ?;)/>/>
thanks -Cheeky
remiX #2
Posted 24 November 2012 - 11:08 AM
fileName = "file"
password = "password!@#$%"

-- readfile
fileRead = fs.open(fileName, "r")
line = fileRead.readLine() -- reads the line
lineAll = fileRead.readAll() -- reads all the text in the line
fileRead.close() -- you must close the file!

-- writing
writeFile = fs.open(fileName, "w") -- 'w' for 'write', use 'a' for 'append' { Write = will overwrite what is in the text ; Append = will add to the file }
writeFile.write(password)
writeFile.close()

See if you can get it right with that ;)/>/>
Luanub #3
Posted 24 November 2012 - 11:10 AM
Here are a couple of different ways to read file contents


local file = fs.open("fileName", "r")
contents = file.read() --should read the whole file

--or read it line by line
sLine = file.readLine()
Lyqyd #4
Posted 24 November 2012 - 11:19 AM
It would be file.readAll() to read the entire file, if you insist on using fs.open.
Luanub #5
Posted 24 November 2012 - 11:24 AM
Ya sorry about that, I usually use IO which you just need to do read().
Lyqyd #6
Posted 24 November 2012 - 11:26 AM
Ah, is the default for :read() to read the whole file? I know you can specify the mode thus:

handle:read("*a") –reads entire file in handle
handle:read("*l") –reads next line in handle

io.open() also gives you the very handy lines iterator:


for line in handle:lines() do
  print(line)
end
cheekycharlie101 #7
Posted 24 November 2012 - 11:33 AM
Cheers Guys, Great Help