Code covered by the BSD License  

Highlights from
Creating File and Folder Trees

Creating File and Folder Trees

by

 

a simple function for sweeping directories and generating trees of files and folders

FileFolderTrees(Datadir)
function  [FoldTree,FileTree] = FileFolderTrees(Datadir)
% XXXXXXXXXXXXXX Written By    Ori Adam,   Nov.2010   XXXXXXXXXXX
% XXXXXXXXXXXXXX Updated Jan.11.2013
% XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Filenum = 0 ;
L = 20000 ; % length of initial tree folder list
D = 2 ; % depth of tree
FoldTree = cell(L,D) ;
FileTree = cell(L,D) ;
FolderDir = dir(Datadir) ;
FoldTree (1,1) = {''} ;
FoldTree (1,2) = {''} ;
LastDir = 1 ;
NewDir  = 1 ;
N = 1 ; 
%% Create a Folder List and a File list of all folders and files in the main directory - Datadir
while (N  > 0 || LastDir == 1) % (NewDir-LastDir  > 0 || LastDir == 1)
    N = 0 ;
    for i = LastDir: NewDir
        FDir = fullfile(Datadir,cell2mat(FoldTree(i,1)),cell2mat(FoldTree(i,2)),'') ;
        if NewDir == 1
            SDir = '' ;
        else
            SDir = fullfile(cell2mat(FoldTree(i,1)),cell2mat(FoldTree(i,2)),'') ;
        end
        FolderDir = dir(FDir) ;
        for j = 1:length(FolderDir)
            if FolderDir(j,1).isdir && ~strncmp(FolderDir(j,1).name,'.',1) 
                N = N + 1 ;
                FoldTree(NewDir + N,1) = {SDir} ;
                FoldTree(NewDir + N,2) = {FolderDir(j,1).name} ;
            elseif ~strcmp(FolderDir(j,1).name,'.') && ~strcmp(FolderDir(j,1).name,'..')
                Filenum = Filenum + 1 ;
                FileTree(Filenum,1) = {SDir} ;
                FileTree(Filenum,2) = {FolderDir(j,1).name} ;
            end
        end
    end
    LastDir = NewDir +1 ;
    NewDir = NewDir + N ;
end

%disp(['Total Number of Directories/Files = ',int2str(NewDir),' / ',int2str(Filenum)]) ;
%% Trim Cell Arrays
FoldT = cell(NewDir,2) ;
FoldT(1:NewDir,1) = FoldTree(1:NewDir,1) ;
FoldT(1:NewDir,2) = FoldTree(1:NewDir,2) ;
FoldTree = FoldT ;
FileT = cell(Filenum,2) ;
FileT(1:Filenum,1) = FileTree(1:Filenum,1) ;
FileT(1:Filenum,2) = FileTree(1:Filenum,2) ;
FileTree = FileT ;

Contact us