X
    Categories: Allgemein

access file systems – recursive function r

I was playing around with recursion. This is a short snippet about iterating through folder structures. It shows all directories and subdirectories within a file path.

library(rlang)  # is_empty() to check if a folder is empty

show.dir <- function(path="/",sleep.time=1){
  if(!is_empty(path)){
    
    print(path);
    print(dir(path,all.files = FALSE, full.names = FALSE, recursive = FALSE));
    Sys.sleep(sleep.time);
        
    #print(charToRaw(paste(dir(path,all.files = FALSE, full.names = FALSE, recursive = FALSE)))); # print HEX for fun

    current.dir <- dir(path,all.files = FALSE, full.names = TRUE, recursive = FALSE);
    
    for(i in 1:length(current.dir)){
      
      #print(i)
      #print(current.dir[i])
    
      if(!is_empty(dir(current.dir[i]))){
      
        #show.dir(current.dir[i])
        #print(dir(current.dir[i]));
        
        #print(charToRaw(paste(dir(current.dir[i]),collapse=""))) # print HEX for fun
        
        #Sys.sleep(sleep.time);
        show.dir(current.dir[i],sleep.time=sleep.time)
        
      }else{print(current.dir[i]);print("empty");}
      
    }
    
  }
}
show.dir(path="/Users/impac/Desktop/test",sleep.time=5)
show.dir()

show.dir(sleep.time=0.3)
show.dir(sleep.time=0.01)

This is the output from a test directory:

[1] "/Users/impac/Desktop/test"
[1] "t1" "t2" "t3" "t4"
[1] "/Users/impac/Desktop/test/t1"
[1] "tt1" "tt2"
[1] "/Users/impac/Desktop/test/t1/tt1"
[1] "ttt1-3"
[1] "/Users/impac/Desktop/test/t1/tt1/ttt1-3"
[1] "empty"
[1] "/Users/impac/Desktop/test/t1/tt2"
[1] "ttt2-3"
[1] "/Users/impac/Desktop/test/t1/tt2/ttt2-3"
[1] "empty"
[1] "/Users/impac/Desktop/test/t2"
[1] "b1" "b2"
[1] "/Users/impac/Desktop/test/t2/b1"
[1] "empty"
[1] "/Users/impac/Desktop/test/t2/b2"
[1] "empty"
[1] "/Users/impac/Desktop/test/t3"
[1] "empty"
[1] "/Users/impac/Desktop/test/t4"
[1] "empty"

 

Martin Stoppacher: