C++
  Home arrow C++ arrow 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++


    (Page 1 of 4 )

    In this fourth part of a five-part series that focuses on streams and files in C++, you will learn how to handle directories. 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). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

    10.10 Creating a Directory

    Problem

    You have to create a directory, and you want to do it portably, i.e., without using OS-specific APIs.

    Solution

    On most platforms, you will be able to use the mkdir system call that is shipped with most compilers as part of the C headers. It takes on different forms in different OSs, but regardless, you can use it to create a new directory. There is no standard C++, portable way to create a directory. Check out Example 10-15 to see how.

    Example 10-15. Creating a directory

    #include <iostream>
    #include <direct.h>

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

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

       if (mkdir(argv[1]) == -1) { // Create the directory
          std::cerr << "Error: " << strerror(errno);
          return(EXIT_FAILURE);
      
    }
    }

    Discussion

    The system call for creating directories differs somewhat from one OS to another, but don't let that stop you from using it anyway. Variations of mkdir are supported on most systems, so creating a directory is just a matter of knowing which header to include and what the function’s signature looks like.

    Example 10-15 works on Windows, but not Unix. On Windows, mkdir is declared in <direct.h>. It takes one parameter (the directory name), returns -1 if there is an error, and sets errno to the corresponding error number. You can get the implementation-defined error text by calling strerror or perror.

    On Unix, mkdir is declared in <sys/stat.h>, and its signature is slightly different. The error semantics are just like Windows, but there is a second parameter that specifies the permissions to apply to the new directory. Instead, you must specify the permissions using the traditional chmod format (see the chmod man page for specifics), e.g., 0777 means owner, group, and others all have read, write, and execute permissions. Thus, you might call it like this on Unix:

      #include <iostream>
      #include <sys/types.h>
      #include <sys/stat.h>

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

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

         if (mkdir(argv[1], 0777) == -1) {  // Create the directory
            std::cerr << "Error: " << strerror(errno);
            return(EXIT_FAILURE);
        
    }
      }

    If you want portability, and don't want to write all the #ifdefs yourself, you should consider using the Boost Filesystem library. You can create a directory using the create_directory function, as shown in Example 10-16, which contains a short program that creates a directory.

    Example 10-16. Creating a directory with Boost

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

    using namespace std;
    using namespace boost::filesystem;

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

       // Parameter checking...
      
    try {
         
    path p = complete(path(argv[1], native));
         
    create_directory(p);
       }
       catch (exception& e) {
          cerr << e.what() << endl;
       }

      return(EXIT_SUCCESS);
    }

    The create_directory function creates a directory identified by the path argument you give it. If that directory already exists, a filesystem_error exception is thrown (derived from the standard exception class). For an explanation of the path class and complete function, both of which are part of the Boost Filesystem library, take a look at the discussion in Recipe 10.7. See Recipe 10.11 for an example of how to remove a directory and all the files it contains. If, on the other hand, portability is not a concern, consult your OS's proprietary filesystem API, which will most likely offer more flexibility.

    See Also

    Recipe 10.12

    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

    - 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++
    - The STL String Class







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