Appending to boost::filesystem::path

2019-03-14 08:10发布

问题:

I have a certain boost::filesystem::path in hand and I'd like to append a string (or path) to it.

boost::filesystem::path p("c:\\dir");
p.append(".foo"); // should result in p pointing to c:\dir.foo

The only overload boost::filesystem::path has of append wants two InputIterators.

My solution so far is to do the following:

boost::filesystem::path p2(std::string(p.string()).append(".foo"));

Am I missing something?

回答1:

#include <iostream>
#include <string>
#include <boost/filesystem.hpp>


int main() {
  boost::filesystem::path p (__FILE__);

  std::string new_filename = p.leaf() + ".foo";
  p.remove_leaf() /= new_filename;
  std::cout << p << '\n';

  return 0;
}

Tested with 1.37, but leaf and remove_leaf are also documented in 1.35. You'll need to test whether the last component of p is a filename first, if it might not be.



回答2:

If it's really just the file name extension you want to change then you are probably better off writing:

p.replace_extension(".foo");

for most other file path operations you can use the operators /= and / allowing to concatenate parts of a name. For instance

boost::filesystem::path p("c:\\dir");
p /= "subdir";

will refer to c:\dir\subdir.



回答3:

With Version 3 of Filesytem library (Boost 1.55.0) it's as easy as just

boost::filesystem::path p("one_path");
p += "_and_another_one";

resulting in p = "one_path_and_another_one".



回答4:

path p;
std::string st = "yoo";
p /= st + ".foo";


回答5:

You can define the + operator yourself such that you can add two boost::filesystem::path variables.

inline boost::filesystem::path operator+(boost::filesystem::path left, boost::filesystem::path right){return boost::filesystem::path(left)+=right;}

Then you can even add a std::string variable (implicit conversion). This is similar to the definition of the operator/ from

include/boost/filesystem/path.hpp:

inline path operator/(const path& lhs, const path& rhs)  { return path(lhs) /= rhs; }

Here is a working example:

main.cpp:

#include <iostream>
#include <string>
#include <boost/filesystem.hpp>

using namespace boost::filesystem;
inline path operator+(path left, path right){return path(left)+=right;}

int main() {
  path p1 = "/base/path";
  path p2 = "/add/this";
  std::string extension=".ext";
  std::cout << p1+p2+extension << '\n';
  return 0;
}

compiled with

g++ main.cpp -lboost_system -lboost_filesystem

produces the output:

$ ./a.out 
"/base/path/add/this.ext"


标签: c++ boost