Appending to boost::filesystem::path

后端 未结 5 1220
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-05 00:53

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.appen         


        
相关标签:
5条回答
  • 2021-02-05 01:29

    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"
    
    0 讨论(0)
  • 2021-02-05 01:31

    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".

    0 讨论(0)
  • 2021-02-05 01:40
    #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.

    0 讨论(0)
  • 2021-02-05 01:43
    path p;
    std::string st = "yoo";
    p /= st + ".foo";
    
    0 讨论(0)
  • 2021-02-05 01:48

    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.

    0 讨论(0)
提交回复
热议问题