Link to home
Start Free TrialLog in
Avatar of Mario271
Mario271Flag for United States of America

asked on

How can I list current directory and subdirectory files as a vector?

I want to list all files in the current directory and all the ones in any of its subdirectories in a vector. I know dir lists the files in the current directory as a struct array. I want to be able to search this list for a filename (as a string), maybe using findstr.
SOLUTION
Avatar of Eyal-f
Eyal-f

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Eyal-f
Eyal-f

As far as searching subdirectories - you can do this with a loop in two ways:

1) Recursively - use dir, find which files in the resulting array are folders, use dir on each of them, etc.

2) You can also generate a list of all the subfolders of a given directory using genpath. so, you could do something like this:

folderstring=genpath('d:\');
folderlist=regexp(folderstring,';','split')

and then loop through the elements of folderlist:

for k=1:length(folderlist)
   filelist=folderlist{k};
   :
end
Two corrections/notes:

1) when using genpath, I think the last character in the vector is a semicolon, so you should skip it in the loop one way or another (e.g. use k=1:length(folderlist)-1 or use an if statement to check the current folder name is a valid folder)
2) if you have a structure array of files generated by the dir structure, the isdir field of a gievn element is 1 if it is a folder.
Avatar of Mario271

ASKER

This is very helpful! Thank you. When I use genpath, am I putting in the name of my directory? I was trying it out and kept getting an empty string. I guess my question is what does the notation d:\ mean? Does it allow genpath to just automatically go through the current directory for subdirectories?
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You need to input the name of the top directory you're searching, so in this example, genpath('d:\') will give a string containing the root of D: and all the folders and subfolders on the partition. for another example, genpath('c:\windows') will give you the windows folder and all its subfolders.
If you omit this argument, you will get the folders in matlab/toolbox.