]> Something Witty Goes Here

codedread

Getting To Know C++ Next: Filesystem

July 12th, 2007

The next version of C++ is going to include some nice, shiny new libraries in its standard namespace. These libraries will really beef up the things that C++ developers want to be able to do in a cross-platform fashion. It’s not clear to me what will happen to the libraries in TR2. I hope things like accessing the bloody file system will make its way into the next version of C++. Here’s a quicky look at how one might do that using Boost.Filesystem.

I’ve really only started using Boost.Filesystem very recently to replace some platform-specific code that accessed the file system so that I could port my code over to OpenSUSE (Linux). That change was pretty much the only thing I had to do because the rest of the program relies on SDL which is already cross-platform.

The code I was using was originally ported from DOS to Windows and used the functions _findfirst(), _findnext() to access a directory contents, iterate through each file and find all files ending in a specific extension. A pretty common operation really, so I thought I’d post this as an example to get people looking at Boost.Filesystem:

#include <string>
#include <vector>
#include <boost/filesystem.hpp>
using namespace boost::filesystem;
using std::string;
using std::vector;

  // get all files ending in .tsg
  vector< string > filenames;
  path dir_path(”data/savegame/”);
  directory_iterator end_it; // [1]
  // loop through each file in the directory
  for(directory_iterator it(dir_path); it != end_it; ++it) {
    // if it’s not a directory and its extension is .tsg [2]
    if( !is_directory(it->status()) && extension(it->path()) == “.tsg” ) {
      // store filename for later use
      filenames.push_back( it->path().string() );
    }
  }

Now your filenames vector contains all the filenames in the directory “data/savegame/” that had an extension “.tsg”. Some notes on this example:

  1. By default, a directory_iterator usefully points to “past the end”
  2. Extensions are case-sensitive on Linux

So basically, a path is pretty much what you’d expect: a location in the filesystem which can either be a directory or a file. You can get the full string representation by calling the member method string(). A directory_iterator allows you to iterate through all items in the path. There are some convenience functions like extension() and basename(). The leaf() member function of a path returns a string holding the last file or directory name in the path object if you ever need that.

Leave a Reply

This is the captcha image, please contact me if you cannot see it

codedread codedread