René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

Count words in files in directories recursively with C++

This is a C++ version of a recursive directory descender. Here is something similar with perl.
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <cctype>
#include <algorithm>
#include <map>
#include <iomanip>
#include <windows.h>

using namespace std;

vector <string> pExts;

map <string, int> words_;

void ScanFile(string sFileName) {
  ifstream f;
  f.open(sFileName.c_str());

  string buf;
  while (f >> buf) {
    words_[buf] ++;
  }

  f.close();
}

void Dir(string sDir, bool bRecursive) {
  WIN32_FIND_DATA findData;

  HANDLE hFind=FindFirstFile((sDir+"\\*.*").c_str(),
      &findData);

  if (hFind == INVALID_HANDLE_VALUE) {
    return;
  }

  // iterate over file names in directory
  do {
    string sFileName(findData.cFileName);
    string suffix = sFileName.substr(
        sFileName.find_last_of(".")+1);

    if (findData.dwFileAttributes & 
        // Directory
        FILE_ATTRIBUTE_DIRECTORY) {

      if (bRecursive) {
        if (sFileName != "." && sFileName != "..") {
          // descent recursively
          Dir(sDir+"\\"+sFileName,true);
        }
      }

    }
    else {
      // File
      
      for (unsigned int i=0; i<pExts.size(); i++) {
        if (pExts[i] == suffix){
          ScanFile(sDir+"\\"+sFileName);
        }
      }
    }

  } while (FindNextFile(hFind, &findData));
}

int _tmain(int argc, _TCHAR* argv[]) {

  pExts.push_back("cpp");
  pExts.push_back("c");
  pExts.push_back("h");

  Dir("C:\\Tsu\\Recursive",true);

  for (map<string,int>::iterator i=words_.begin();
      i!=words_.end(); i++) {
        cout << setw(40) << i->first << " " 
             << setw(4) << i->second << endl;

  }

  return 0;
}