C++
  Home arrow C++ arrow Page 4 - Paths and Files
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++

Paths and Files
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 2
    2008-11-13

    Table of Contents:
  • Paths and Files
  • 10.15 Extracting a Path from a Full Path and Filename
  • 10.16 Replacing a File Extension
  • 10.17 Combining Two Paths into a Single Path

  • 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


    Paths and Files - 10.17 Combining Two Paths into a Single Path


    (Page 4 of 4 )

    Problem

    You have two paths and you have to combine them into a single path. You may have something like /usr/home/ryan as a first path, and utils/compilers as the second, and wish to get /usr/home/ryan/utils/compilers, without having to worry whether or not the first path ends with a path separator.

    Solution

    Treat the paths as strings and use the append operator, operator+=, to compose a full path out of partial paths. See Example 10-26.

    Example 10-26. Combining paths

    #include <iostream>
    #include <string>

    using std::string;

    string pathAppend(const string& p1, const string& p2) {

       char sep = '/';
      
    string tmp = p1;

    #ifdef _WIN32
     
    sep = '\';
    #endif

      if (p1[p1.length()] != sep) { // Need to add a
        
    tmp += sep;                // path separator
        
    return(tmp + p2);
     
    }
      else
         return(p1 + p2);
    }

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

      string path = argv[1];

      std::cout << "Appending somedir\\anotherdir is ""
                << pathAppend(path, "somedir\\anotherdir") << ""\n";
    }

    Discussion

    The code in Example 10-26 uses strings that represent paths, but there's no additional checking on the path class for validity and the paths used are only as portable as the values they contain. If, for example, these paths are retrieved from the user, you don't know if they're using the right OS-specific format, or if they contain illegal characters.

    For many other recipes in this chapter I have included examples that use the Boost Filesystem library, and when working with paths, this approach has lots of benefits. As I discussed in Recipe 10.7, the Boost Filesystem library contains a path class that is a portable representation of a path to a file or directory. The operations in the Filesystem library mostly work with path objects, and as such, the path class can handle path composition from an absolute base and a relative path. (See Example 10-27.)

    Example 10-27. Combining paths 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 {
         
    // Compose a path from the two args
         
    path p1 = complete(path(argv[2], native),
                            
    path(argv[1], native));
          cout << p1.string() << endl;

          // Create a path with a base of the current dir
         
    path p2 = system_complete(path(argv[2], native));
         
    cout << p2.string() << endl;
      
    }
       catch (exception& e) {
          cerr << e.what() << endl;
       }

      return(EXIT_SUCCESS);
    }

    The output of the program in Example 10-27 might look like this:

      D:\src\ccb\c10>bin\MakePathBoost.exe d:\temp some\other\dir
      d:/temp/some/other/dir
      D:/src/ccb/c10/some/other/dir

    or:

      D:\src\ccb\c10>bin\MakePathBoost.exe d:\temp c:\WINDOWS\system32
      c:/WINDOWS/system32
      c:/WINDOWS/system32

    What you can see here is that complete and system_complete merge paths when possible, or return the absolute path when merging paths makes no sense. For example, in the first output, the first argument given to the program is an absolute directory and the second is a relative directory. complete merges them together and produces a single, absolute path. The first argument to complete is the relative path, and the second is the absolute path, and if the first argument is already an absolute path, the second argument is ignored. That's why in the second output you can see that the argument "d:\temp" is ignored since the second argument I give is already an absolute path.

    system_complete only takes a single argument (the relative path in this case) and appends it to the current working directory to produce another absolute path. Again, if you give it a path that is already absolute, it ignores the current working directory and simply returns the absolute path you gave it.

    These paths are not reconciled with the filesystem though. You have to explicitly test to see if a path object represents a valid filesystem path. For example, to check if one of these paths exists, you can use the exists function on a path:

      path p1 = complete(path(argv[2], native),
                         path(argv[1], native));
      if (exists(p1)) {
         // ...

    There are many more functions you can use to get information about a path: is_directory, is_empty, file_size, last_write_time, and so on. See the Boost Filesystem library documentation at www.boost.org for more information.

    See Also

    Recipe 10.7


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · 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 4 Hosted by Hostway
    Stay green...Green IT