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

List all Files of a Computer

Started by Wilma456, 28 August 2016 - 09:47 AM
Wilma456 #1
Posted 28 August 2016 - 11:47 AM
How can I get a Table with all files on a Computer? fs.list shows only one directory. The files should have the corect path, so that I can work with them.
KingofGamesYami #2
Posted 28 August 2016 - 01:21 PM
Use fs.list recursively.


local tFiles = {}
local scanDir
function scanDir( sDir )
  local t = fs.list( sDir ) 
  for k, v in pairs( t ) do
    local sFullName = fs.combine( sDir, v )
    if fs.isDir( sFullName ) then
      scanDir( sFullName )
    else
      tFiles[ #tFiles + 1 ] = sFullName
    end
  end
end
CrazedProgrammer #3
Posted 28 August 2016 - 02:01 PM
Use fs.list recursively.
Whilst this will work, it's a bad practice to use functions recursively, since it can cause stack overflow exceptions.
Use a stack:

local files = { }
local stack = { "" }
while #stack > 0 do
    local dir = stack[1]
    table.remove(stack, 1)
    local t = fs.list(dir)
    for i = 1, #t do
        local path = dir.."/"..t[i]
        if fs.isDir(path) then
            table.insert(stack, 1, path)
        else
            files[#files + 1] = path
        end
    end
end

Note: this will also include all files in /rom.
If you want to ignore the /rom directory, use this:

local files = { }
local stack = { "" }
while #stack > 0 do
    local dir = stack[1]
    table.remove(stack, 1)
    if dir ~= "/rom" then
        local t = fs.list(dir)
        for i = 1, #t do
            local path = dir.."/"..t[i]
            if fs.isDir(path) then
                table.insert(stack, 1, path)
            else
                files[#files + 1] = path
            end
        end
    end
end
Edited on 28 August 2016 - 12:04 PM