Here's some rudimentary code that does directory traversal recursively. Useful for inspecting the contents of a directory subtree. Sorting the directory information or inspecting file details within directories is beyond the scope of this routine.
Recursive Directory Traversal
// Recursive subdirectory traversal
// The list of directories is unsorted. but complete
// FAT32 visitation order is roughly by create date
// NTFS visitation order is roughly alphabetical (NOT guaranteed)
// Dirs can be written to a file, then sorted and read back in or
// passed to dynamic sort routine. Your choice.
// A sorted list can be used to step through the directories "in order"
#include <stdlib.h>
#include <stdio.h>
#include <dir.h>
#include <dos.h>
int main(int argc, char *argv[])
{
// PROTOTYPE
void recurse(int &dircount); // Make dir counter accessible for update
char curdir[MAXDIR];
int dircount=0;
// Switch to directory you want to start from first ...
// chdir("somewhere");
getcwd(curdir,MAXDIR); // Get full name of starting directory
printf("%s\n",curdir); // Print, write to file, whatever.
// Might look for specific records here before going to subdirs
// Start processing this dir's subdirs
recurse(dircount);
// All done, display count
printf("Directories visited: %d\n",dircount);
return dircount;
}
// BODY
void recurse(int &dircount)
{
char curdir[MAXDIR];
int done;
struct ffblk d;
dircount++;
// Scan all records in this dir, looking for subdirectories
for (done=findfirst("*.*",&d,FA_DIREC); done==0; done=findnext(&d))
{
// We've found a directory
if ((d.ff_attrib & FA_DIREC) == FA_DIREC)
{
// Skip over self & parent directory records
if (strcmp(d.ff_name,".") == 0 || strcmp(d.ff_name,"..") == 0)
continue;
// Switch to the new directory
chdir(d.ff_name);
// "Visit" the new directory
getcwd(curdir,MAXDIR); // Get its name
printf("%s\n",curdir); // Print it, etc.
// Could inspect directory for specific records at this point
// Look for its subdirectories
recurse(dircount);
}
}
// Switch up to parent directory
// Now that all directories at this
// level have been processed
chdir("..");
return;
}
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.