List Dirs
2002-09-08 23:57:02
Category: cpp:files
Description: Using recursion list all of the sub directories starting at a given path.
Author: detour
Viewed: 2797
Rating: (7 votes)


 
			
/* rec_dir_list.cpp by detour@metalshell.com
 *
 * List all sub directories starting at a given path.
 *
 * http://www.metalshell.com
 *
 */
 
#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;
}