how to use C++ to get the folder/directory name, but not the path of one file? Especially boost::filesystem; [duplicate]

|▌冷眼眸甩不掉的悲伤 提交于 2020-08-07 04:03:23

问题


    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.


回答1:


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




回答2:


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';



回答3:


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();



来源:https://stackoverflow.com/questions/39275465/how-to-use-c-to-get-the-folder-directory-name-but-not-the-path-of-one-file-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!