8
    std::string file="C:\\folder1\\folder2\\folder3.txt";
fs::path file_path(file);
fs::path file_dir=file_path.parent_path();// "C:\\folder1\\folder2";
std::string str_path=file_path.string();
std::string str_dir=file_dir.string();
std:string str_folder=str_path.erase(0,str_dir()+1);// return folder2

This is the method I used. It works for me, but it looks ugly. So I prefer to look for boost::filesystems or other elegant code. Notes: THis question is not duplicated and sligtly different from the question proposed Getting a directory name from a filename. My interest is to find the filename but not the whole directory path.

Community
  • 1
  • 1
Pengju Zhao
  • 1,439
  • 3
  • 14
  • 17

3 Answers3

8

You can use parent_path to get rid of the last element in the path, then filename to get the last element. Example: include boost/filesystem.hpp and iostream

namespace fs = boost::filesystem;
int main()
{
   fs::path p ("/usr/include/test");
   std::cout << p.parent_path().filename() << "\n";
}

should print "include".

midor
  • 5,487
  • 2
  • 23
  • 52
0

You can use path iterators to find the last directory as well. It's not really much prettier though.

Example

boost::filesystem::path p{"/folder1/folder2/folder3.txt"};
boost::filesystem::path::iterator last_dir;
for (auto i = p.begin(); i != p.end(); ++i)
{
    if (*i != p.filename())
        last_dir = i;
}
std::cout << *last_dir << '\n';

The output of the above code should be "folder2".

The above code uses Unix paths, but the principle is the same for Windows paths.

Same results from

last_dir = p.end();
--last_dir;
--last_dir;
std::cout << *last_dir << '\n';
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

This question was asked in another stack post. Boost filesystem

In your case you can do something like this.

boost::filesystem::path p("C:\\folder1\\folder2\\folder3.txt"); boost::filesystem::path dir = p.parent_path();

Community
  • 1
  • 1
Nate
  • 21
  • 6
  • In its current form this answer should be merely a comment. Please replicate the example here, instead of posting only the link. – πάντα ῥεῖ Sep 01 '16 at 16:04
  • This question is a duplicate of link that was posted. – Nate Sep 01 '16 at 19:40
  • If you have enough reputation you may flag the question as a duplicate, but posting the link as an answer isn't acceptable. THX for pointing out though, I hammered the question as a dupe now. Please gain enough reputation to comment and flag please. As mentioned posting such as an answer isn't actually acceptable. – πάντα ῥεῖ Sep 01 '16 at 19:46