Search here

Pages

Thursday, August 11, 2011

Program using recursion to List all sub directories starting at a given path

#include <iostream>
#include <string>
#include <io.h>
 
using namespace std;
 
#define DIR "c:"
 
int rec_dir_list(string path) {
  static int count = 0;
  struct _finddata_t  c_file;
  long fh;
  
 
  string t_path = path;
  t_path += "\\*.*";
 
  if((fh=_findfirst(t_path.c_str(),&c_file)) != -1)
    while(_findnext(fh, &c_file) == 0)
      // ignore '.' and '..'
      if(strncmp(c_file.name, ".", 1) != 0
         && strncmp(c_file.name, "..", 2) != 0) {
        if((c_file.attrib & _A_SUBDIR) == _A_SUBDIR) {
          rec_dir_list(path + "\\" + c_file.name);
          cout << "DIR: " << path << "\\" << c_file.name << endl;
          count++;
        }
      }
 
  return count;
}
 
int main() {
 
  cout << "There are " << rec_dir_list(DIR)
       << " sub directories\n";
 
  return 0;
}

0 comments

Post a Comment