Representing a directory tree as a recursive list

perl recursive directory walk
c program to list all files in a directory and sub-directories
perl find all files in directory recursively
c program to search for a file in a directory
c program to read all files in a directory
c list files in directory
recursive dirent
list files in folder cpp

I am stuck with a certain task. What I want is a function that, given a directory path, would return a recursive-list as an output.

The output should be of the form myList$dir$subdir$subdir$fullFilePath

So basically I want to represent a directory tree as a certain list. I obtain all the files, get all the subdirectories for each of the file, but I am stuck as to how to throw it all into a list with multiple levels.

Here is a solution using recursion:

tree.list <- function(file.or.dir) {
    isdir <- file.info(file.or.dir)$isdir
    if (!isdir) {
        out <- file.or.dir
    } else {
        files <- list.files(file.or.dir, full.names   = TRUE,
                                         include.dirs = TRUE)
        out <- lapply(files, tree.list)
        names(out) <- basename(files)
    }
    out
}

I have tested it here on a small directory

test.dir <- tree.list("./test")
test.dir
# $a
# $a$`1.txt`
# [1] "./test/a/1.txt"
# 
# $a$aa
# $a$aa$`2.txt`
# [1] "./test/a/aa/2.txt"
# 
# $b
# $b$`3.txt`
# [1] "./test/b/3.txt"

If this is too slow for your needs, I would consider reading all the files into a single call to list.files with recursive = TRUE then do a bit of parsing.

C program to list all files in a directory recursively, h header file. It returns pointer to a structure dirent type representing directory entry at the current position in  tree dir1. From the above outputs, it is clear that running the tree dir1 gives a list of dir1 directory and its subdirectories and files. The base directory is dir1. Then you have all the child directroies. All all the child directories have additional files and directories (say grand directories), and so on.

Here is an ugly hack.

mypath <- 'a/b/c/d'


makelist <- function(filepath, fsep = '/'){

  unlisted <- unlist(strsplit(filepath, fsep))

  nsubs <- length(unlisted)

  mylistcall <- paste(paste(rep('list(', nsubs), unlisted, collapse = '='), 
    '= NULL', paste(rep(')', nsubs), collapse = ''))


  mylist <- eval(parse(text = mylistcall))
  return(mylist)
  }

makelist(mypath)

$a
$a$b
$a$b$c
$a$b$c$d
NULL   

Remembering

fortune(106)

If the answer is parse() you should usually rethink the question.
   -- Thomas Lumley
      R-help (February 2005)

In this case however, I would say I should be rethinking the answer.

Understanding recursive subroutines, Every directory listing contains the . representing the current directory, and .. representing the parent director. We want to skip them, so we call next when we  One very nice property of this list of lists approach is that the structure of a list representing a subtree adheres to the structure defined for a tree; the structure itself is recursive! A subtree that has a root value and two empty lists is a leaf node.

Here's a shorter variant of @flodel's wonderful solution using the purrr package:

library( purrr )
tree_list <- function( file_or_dir ) {
  f <- partial(list.files, full.names=TRUE, include.dirs=TRUE) %>%
         compose(tree_list, .)
  file_or_dir %>% set_names( basename(.) ) %>% map_if(dir.exists, f)
}

The first line defines a function f that expands its argument using list.files( ..., full.names=TRUE, include.dirs=TRUE) then applies tree_list() to the expansion.

The second line applies the defined function f to all directories in the original argument.

Linux tree command help and examples, tree is a recursive directory listing program that produces a depth-indented When directory arguments are given, tree lists all the files and/or  shutil.copytree() method recursively copies an entire directory tree rooted at source (src) to the destination directory. The destination directory, named by (dst) must not already exist. It will be created during copying. Permissions and times of directories are copied with copystat() and individual files are copied using shutil.copy2().

Practical Recursion: Implementing a File Tree View in React , To create a representation of a file tree in JavaScript, the object literal as a list of files/folders in the root directory, and expanded/contracted  The first line defines a function f that expands its argument using list.files( , full.names=TRUE, include.dirs=TRUE) then applies tree_list() to the expansion. The second line applies the defined function f to all directories in the original argument.

Linux see directory tree structure using tree command, Linux see directory tree structure - Explains how to use Linux tree command to list It is a recursive directory listing program that produces a depth indented listing of files. -J Prints out an JSON representation of the tree. You can easily convert above function to work for recursive directory listing. Check below program if facing difficulties implementing it recursive way. Program to list all files and sub-directories of a directory recursively /** * C program to list contents of a directory recursively.

Java program to List all files in a directory and nested sub , It is quite easy to observe simple recursion pattern in above problem. Recursive Algorithm : 1. Create File object for main directory. 2. Get array of files for  In some cases however, using recursion feels more natural than using iteration. Traversing a tree is one of them. We can create recursive components in Vue.js and any other framework by following the same mechanics. Creating a Tree Component. Imagine a component that must render a tree structure, for example showing a directory tree:

Comments
  • Thanks! this is so elegant it hurts.
  • It won't be too slow for now. And for the parsing - I would still have no idea how to make a recursive list after parsing. after strsplit I would have something like: list(dir=myDir, subdir1=mySubdir1, subdir2=mySubdir2, file=myFile). For loop would not work with list[["myDir"]][[mySubdir1]][[mySubdir2]][[myFile]] <- file, since I can't specify the wanted number of levels in a loop. Thanks again for this answer.
  • Thanks! flodel came up with a more neat answer. Were this not the case I would be gladly accepted your answer.
  • by the way just noticed - what is that fortune thing you have going?
  • @KarolisKoncevičius. see cran.r-project.org/web/packages/fortunes/index.html
  • I wish I had seen this before doing it the hard way!