Recursive Directory Traversal

banders7 0 Tallied Votes 237 Views Share

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 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[])
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

// All done, display count
printf("Directories visited: %d\n",dircount);

return dircount;

void recurse(int &dircount)
char curdir[MAXDIR];

int done;
struct ffblk d;


// 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)

      // Switch to the new directory

      // "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
// Switch up to parent directory
// Now that all directories at this
// level have been processed