Recursive Directory Listing

okibi spam at ratedo.com
Fri Feb 15 02:59:49 PST 2008


okibi Wrote:

> Tim Burrell Wrote:
> 
> > okibi wrote:
> > > Hello,
> > > 
> > > I was wondering if anyone could tell me how I would go about doing this. I need a function that can list all the files and directories in a given directory, and return an array that I can use that can reference each file, each folder, and each file within each subfolder. Is this possible?
> > > 
> > > Thanks!
> > 
> > tango.io.FileScan :).
> > 
> > If you're using Phobos, a recursive file scanner is pretty much the
> > easiest thing you can write!
> > 
> > Pseudo code:
> > 
> > scan(char [] Path, ref char [][] Paths) {
> > 	Paths ~= Path
> > 
> > 	if (!Path.isDirectory)
> > 		return
> > 
> > 	ListOfPaths = getContentsOfDir(Path)
> > 	foreach (Item; ListOfPaths)
> > 		scan(Path)
> > }
> > 
> > Obviously you can get more creative and store an array of structures
> > which contain file system information such as whether or not the path is
> > a file or a directory, etc, but that's the basic idea.
> > 
> > Even if you're not using Tango, you can always look at the source code
> > to see how they are doing it:
> > http://dsource.org/projects/tango/docs/current/source/tango.io.FileScan.html
> > 
> > Hope this helps!
> 
> Actually, I was wondering if D had a function (or function within Phobos) that allowed recursive directory scanning. Anyways, here's what I wrote:
> 
> void dirList(char[] path)
> {
> 	if (!isdir(path))
> 		writefln("File: ", path);
> 	else
> 	{
> 		writefln("Directory: ", path);
> 		char[][] pathsList = listdir(path);
> 		char[][] dirs;
> 		char[][] files;
> 		foreach (item; pathsList)
> 		{
> 			if (isdir(path~"/"~item))
> 				dirs ~= path~"/"~item;
> 			else
> 				files ~= path~"/"~item;
> 		}
> 		foreach (file; files)
> 			writefln("File: ", file);
> 		foreach (dir; dirs)
> 			dirList(dir);
> 	}
> }
> 
> Can this be optimized at all?
> 
> Thanks!

In reply to myself, that code will only pick up the first directory in each subdirectory.


More information about the Digitalmars-d-learn mailing list