Home arrow C++ arrow Page 4 - Paths and Files
C++

Paths and Files


In this conclusion to a five-part article series on streams and files in C++, you will learn how to extract a filename from a full path, and more. 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.

Author Info:
By: O'Reilly Media
Rating: 5 stars5 stars5 stars5 stars5 stars / 2
November 13, 2008
TABLE OF CONTENTS:
  1. · Paths and Files
  2. · 10.15 Extracting a Path from a Full Path and Filename
  3. · 10.16 Replacing a File Extension
  4. · 10.17 Combining Two Paths into a Single Path

print this article
SEARCH DEVARTICLES

TOOLS YOU CAN USE

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.

blog comments powered by Disqus
C++ ARTICLES

- Intel Threading Building Blocks
- Threading Building Blocks with C++
- 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++

Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 



© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 1 - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials