So there I was writing in a file called ‘7.txt’, and I thought to myself, hey! It sure would be nice to know how many words I’ve written total! Naturally I also have 1 through 6 .txt. Each file is a chapter, it’s a pretty simple system. I could have gotten a calculator or pasted all the files together or something, and that’d be fine now, but I’m sure I’ll want to count the words again. So I went looking for an app to do it. The best I found was a line counter, which is just close enough to what I want to be entirely useless.

Next best option? Write it! So I did, real quick in C++ with lots of invocations of boost. The app is at http://www.omnisu.com/files/wc.zip Inside, you’ll find ‘wc.exe’ and ‘WordCount.cpp’. If you don’t know C++, well, ignore WordCount.cpp – but the source is there, just in case you do know C++ and want to peek. The source is 140 words long!

The usage is pretty simple : wc <mask>, where <mask> is a regular-expression used to match filenames. If you don’t know regular expressions either, well, you might have some trouble using it. But this should help. If you want to count all the .txt files in a directory, use the command ‘wc .*\.txt’ For my files, I happened to use ‘wc [0-9]\.txt’

Oh look, the source is also here. D:!

#include <iostream>
#include <fstream>
#include <string>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/regex.hpp> 

bool is_whitespace(char a)
{
	return (a == ' ' || a == '\t' || a == '\n' || a == '\r');
}

int main(int argc, char* argv[])
{
	boost::filesystem::path dir_path( boost::filesystem::initial_path() );

	if ( argc <= 1 )
	{
		std::cout << "\nusage:   wordcount [mask]" << std::endl;
		return 0;
	}

	boost::regex expression(argv[1]);

	int word_count = 0;
	std::string word;

	boost::filesystem::directory_iterator end_iter;
	for ( boost::filesystem::directory_iterator dir_itr( dir_path ); dir_itr != end_iter;	++dir_itr )
	{
		std::string file_name = dir_itr->leaf();
		if (regex_match(file_name,expression))
		{
			std::cout << "Reading file " << file_name << std::endl;

			std::ifstream file(file_name.c_str());
			while ( file >> word) ++word_count;
		}
	}

	std::cout << word_count << std::endl;
	return 0;

}