Jump to content




how to read a file?


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

#1 cheekycharlie101

  • Members
  • 231 posts

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

#2 remiX

  • Members
  • 2,076 posts
  • LocationSouth Africa

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 ;)/>

#3 Luanub

    Lua Nub

  • Members
  • 1,135 posts
  • LocationPortland OR

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()


#4 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 24 November 2012 - 11:19 AM

It would be file.readAll() to read the entire file, if you insist on using fs.open.

#5 Luanub

    Lua Nub

  • Members
  • 1,135 posts
  • LocationPortland OR

Posted 24 November 2012 - 11:24 AM

Ya sorry about that, I usually use IO which you just need to do read().

#6 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

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


#7 cheekycharlie101

  • Members
  • 231 posts

Posted 24 November 2012 - 11:33 AM

Cheers Guys, Great Help





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users