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

Help me! fs.open

Started by Konlab, 16 May 2014 - 03:30 PM
Konlab #1
Posted 16 May 2014 - 05:30 PM
Hi!
How to use fs.open() and how to edit files with programs?
Please don't give me links to computercft wiki, because I don't understand the entire cc wiki.
Thanks.
Zudo #2
Posted 16 May 2014 - 05:58 PM

local fileHandle = fs.open("/path/to/file", "w") -- Open /path/to/file with write permissions

fileHandle.write("Some Text") -- Replaces the current contents of /path/to/file with "Some Text"

fileHandle.close() -- Stops editing, you should always do this.
Konlab #3
Posted 16 May 2014 - 06:04 PM
Thanks very much. And please say me how can I read things.
Also again thanks very much I've waited 1 month ago for this, all people gave only links to wikipedia.
Zudo #4
Posted 16 May 2014 - 06:07 PM
Sure.


local fileHandle = fs.open("/path/to/file", "r") -- Open /path/to/file with read permissions

local contents = fileHandle.readAll() -- Saves the contents of /path/to/file to the contents variable

fileHandle.close() -- Stops reading
Edited on 17 May 2014 - 01:02 PM
Konlab #5
Posted 16 May 2014 - 06:16 PM
And the contents variable will a table?
If table then the indexes are for lines?

Thanks
Zudo #6
Posted 16 May 2014 - 06:21 PM
No, contents will be a string containing the entire file. If you wanted to get an individual line, you would need to do something like this.

**WARNING - UNTESTED BAD CODE**


local fileHandle = fs.open("/path/to/file", "r") -- Open /path/to/file with read permissions

local lineToGet = 5 -- Which line to read?
local lineContents = "" -- Will contain the contents of that line


for _ = 1, lineToGet do -- Repeats until it reaches the right line.
 lineContents = fileHandle.readLine() -- Reads the line.
end

fileHandle.close()
Edited on 16 May 2014 - 04:22 PM
Konlab #7
Posted 16 May 2014 - 06:22 PM
Thanks very much :-)
It helped a lot.
Thanks very much
:-) :-)
Zudo #8
Posted 16 May 2014 - 06:23 PM
No problem :)/>
Konlab #9
Posted 17 May 2014 - 06:57 AM
And fs.writeLine() works too?
Zudo #10
Posted 17 May 2014 - 02:20 PM
And fs.writeLine() works too?

Do you want to append text onto the end of the file? writeLine() just appends an EOL character to what you entered. If you want to append text, change:


local fileHandle = fs.open("/path/to/file", "w") -- Open /path/to/file with write permissions

to


local fileHandle = fs.open("/path/to/file", "a") -- Open /path/to/file with append permissions
Edited on 17 May 2014 - 12:23 PM
theoriginalbit #11
Posted 17 May 2014 - 02:33 PM
No, contents will be a string containing the entire file.
No. Given this line

local contents = fileHandle.read()
only the first line of the file would be in contents, you need to use readAll to have all the contents.