C++
  Home arrow C++ arrow Page 3 - Directories in C++
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C++

Directories in C++
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 2
    2008-11-06

    Table of Contents:
  • Directories in C++
  • 10.11 Removing a Directory
  • 10.12 Reading the Contents of a Directory
  • 10.13 Extracting a File Extension from a String

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Directories in C++ - 10.12 Reading the Contents of a Directory


    (Page 3 of 4 )

    Problem

    You need to read the contents of a directory, most likely to do something to each file or subdirectory that's in it.

    Solution

    To write something portable, use the Boost Filesystem library's classes and functions. It provides a number of handy utilities for manipulating files, such as a portable path representation, directory iterators, and numerous functions for renaming, deleting, and copying files, and so on. Example 10-19 demonstrates how to use a few of these facilities.

    Reading the Contents of a Directory 

    Example 10-19. Reading a directory

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

    using namespace boost::filesystem;

    int main(int argc, char** argv) {

       if (argc < 2) {
          std::cerr << "Usage: " << argv[0] << " [dir name]\n";
          return(EXIT_FAILURE);
      
    }

       path fullPath =   // Create the full, absolute path name
         system_complete(path(argv[1], native));

       if (!exists(fullPath)) {
          std::cerr << "Error: the directory " << fullPath.string()
                    << " does not exist.\n";
          return(EXIT_FAILURE);
       }

       if (!is_directory(fullPath)) {
          std::cout << fullPath.string() << " is not a directory!\n";
          return(EXIT_SUCCESS);
       }

       directory_iterator end;
       for (directory_iterator it(fullPath);
           it != end; ++it) {         // Iterate through each
                                     
    // element in the dir,
         std::cout << it->leaf();     // almost as you would
         if (is_directory(*it))       // an STL container
            std::cout << " (dir)"; 
        
    std::cout << '\n';
      }

      return(EXIT_SUCCESS);
    }

    Discussion

    Like creating or deleting directories (see Recipes 10.10 and 10.11), there is no standard, portable way to read the contents of a directory. To make your C++ life easier, the Filesystem library in the Boost project provides a set of portable routines for operating on files and directories. It also provides many more--see the other recipes in this chapter or the Boost Filesystem web page at www.boost.com for more information.

    Example 10-19 is a simple directory listing program (like ls on Unix or dir on MSDOS). First, it builds an absolute pathname out of the argument passed to the program, like this:

      path fullPath = complete(path(argv[1], native));

    The data type of a path is called, appropriately, path. This is the type that the filesystem routines operate on, and is easily convertible to a string by calling path::string. Once the path has been assembled, the program checks its existence (with exists), then checks to see if it is a directory with another utility function, is_directory. If it is, then everything is in good shape and it can proceed to the real work of listing the directory contents.

    There is a class called directory_iterator in filesystem that uses standard iterator semantics, like the standard containers, to allow you to use an iterator like you would a pointer to a directory element. Unlike standard containers, however, there is no end member function you can call on a directory that represents one-past-the-last-element (i.e., vector<T>::end). Instead, if you create a directory_iterator with the default constructor, it represents an end marker that you can use for comparison to determine when you are done. So do this:

      directory_iterator end;

    and then you can create an iterator from your path, and compare it to end, like this:

      for (directory_iterator it(fullPath);
         
    it != end; ++it) {
       
    // do whatever you want to *it
       
    std::cout << it->leaf();
      }

    The leaf member function returns a string representing the element referred to by a path, and not the full path itself, which is what you get if you call the string member function.

    If you have to write something that is portable, but for some reason you cannot use Boost, take a look at the Boost code itself. It contains #ifdefs that deal with (for the most part) Windows versus Posix OS interface environments and path particulars, such as drive letters versus device names.

    See Also

    Recipes 10.10 and 10.11

    More C++ Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "C++ Cookbook," published by O'Reilly. We...
     

    Buy this book now. This article is excerpted from chapter 10 of the C++ Cookbook, written by Ryan Stephens, Christopher Diggins, Jonathan Turkanis and Jeff Cogswell (O'Reilly; ISBN: 0596007612). Check it out today at your favorite bookstore. Buy this book now.

    C++ ARTICLES

    - Video Memory Programming in Text Mode
    - More Tricks to Gain Speed in Programming Con...
    - Easy and Efficient Programming for Contests
    - Preparing For Programming Contests
    - Programming Contests: Why Bother?
    - Polymorphism in C++
    - Overview of Virtual Functions
    - Inheritance in C++
    - Extending the Basic Streams in C++
    - Using Stringstreams in C++
    - Custom Stream Manipulation in C++
    - General Stream Manipulation in C++
    - Serialize Your Class into Streams in C++
    - Advanced File Handling with Streams in C++
    - File Handling and Streams in C++







    © 2003-2010 by Developer Shed. All rights reserved. DS Cluster 3 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek