Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the parent folder of a directory using boost::filesystem

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.

like image 751
James Franco Avatar asked Aug 14 '15 21:08

James Franco


People also ask

What is the function of boost file system?

Chapter 35. Boost.Filesystem - Files and Directories The member functions presented with boost::filesystem::path simply process strings. They access individual components of a path, append paths to one another, and so on. In order to work with physical files and directories on the hard drive, several free-standing functions are provided.

What is the use of is_directory in boost?

This function returns an object of type boost::filesystem::file_status, which can be passed to additional helper functions for evaluation. For example, boost::filesystem::is_directory () returns true if the status for a directory was queried.

How do I get the size of a file in boost?

The Boost.Filesystem file_size function returns a uintmax_t containing the size of the file named by the argument. The declaration looks like this: For now, all you need to know is that class path has constructors that take const char * and other string types.

What is the return value of Boost::FileSystem::error_code?

The return value is of type boost::uintmax_t, which is a type definition for unsigned long long. The type is provided by Boost.Integer. Example 35.11 uses an object of type boost::system::error_code, which needs to be evaluated explicitly to determine whether the call to boost::filesystem::file_size () was successful. Example 35.12.


2 Answers

There is method parent_path, check the docs.

like image 63
Andrey Avatar answered Sep 19 '22 07:09

Andrey


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.

like image 38
caps Avatar answered Sep 21 '22 07:09

caps