The Artima Developer Community
Sponsored Link

The C++ Source
Listing 1 - Using the UNIX Directory Navigation Functions

This program shows how to use UNIX-style directory processing functions. It is from the article Reading Unix-style Directories via STL-compliant Sequences.

#include <dirent.h>   // opendir(), readdir(), closedir()
#include <sys/stat.h> // stat()

#include <algorithm>  // std::copy
#include <iterator>   // std::ostream_iterator
#include <iostream>   // std::cout, std::endl
#include <string>     // std::string
#include <vector>     // std::vector

using std::copy;
using std::cout;
using std::endl;
using std::ostream_iterator;
using std::string;
using std::vector;

const char HOME[] = "/home/matty/";

int main()
{
  vector<string>  dirNames;
  DIR             *dir = opendir(HOME);

  if(NULL != dir)
  {
    struct dirent *entry;
    for(; NULL != (entry = readdir(dir)); )
    {
      struct stat st;

      // Skip dots
      if( '.' == entry->d_name[0] &&
          ( '\0' == entry->d_name[1] ||
            ( '.' == entry->d_name[1] &&
              '\0' == entry->d_name[2])))
      {
        // do nothing
      }
      else
      {
        if(0 == stat((string(HOME) + entry->d_name).c_str(), &st))
        {
          if(S_IFDIR == (st.st_mode & S_IFDIR))
          {
            dirNames.push_back(entry->d_name);
          }
        }
      }
    }
    closedir(dir);
  }

  cout << "Dumping subdirectories of " << HOME << endl;
  copy(dirNames.begin(), dirNames.end(), ostream_iterator<string>(cout, "\n"));

  return 0;
}

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2014 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us