10

Suppose I have the following folder

std::string m("C:\MyFolderA\MyFolderB\MyFolderC");
boost::filesystem::path p(m);

Is there anyway for me to extract the parent of this folder. I want to get the string MyFolderB. from the above path.

Ad N
  • 7,930
  • 6
  • 36
  • 80
James Franco
  • 4,516
  • 10
  • 38
  • 80

2 Answers2

11

There is method parent_path, check the docs.

Andrey
  • 59,039
  • 12
  • 119
  • 163
  • Thanks for the link. That was very helpful – James Franco Aug 14 '15 at 22:51
  • Note that the OP wanted to get the name of the "MyFolderB" folder. However, `parent_path()` returns the **full path** to the "MyFolderB" folder, so we may need to use [`boost::filesystem::path.filename()`](https://www.boost.org/doc/libs/1_53_0/libs/filesystem/doc/reference.html#path-filename) to extract the folder name. – li ki Mar 18 '22 at 02:18
1

Or, if you prefer a string manipulation method.

#include <algorithm>

const std::string m("C:\\MyFolderA\\MyFolderB\\MyFolderC");
const std::string slash("\\");
auto last_slash(std::find_end(std::cbegin(m), 
                              std::cend(m), 
                              std::cbegin(slash),
                              std::cend(slash)));
auto second_to_last_slash(std::find_end(std::cbegin(m), 
                                        last_slash,
                                        std::cbegin(slash), 
                                        std::cend(slash)));

const std::string parent(++second_to_last_slash, last_slash);

Live on Coliru, if you're into that.

caps
  • 1,225
  • 14
  • 24
  • Good point! The user's question used Windows-style paths, so that is how I solved it. I believe this would work with an arbitrary string `m` if `slash` were `#ifdef`ed to be initialized as `"/"` in Linux contexts. – caps Apr 05 '18 at 16:40