parent_path() with or without trailing slash

后端 未结 4 853
北海茫月
北海茫月 2020-12-19 02:56

As explained in the documentation, the expected output of the following is:

boost::filesystem::path filePath1 = \"/home/user/\";
cout << filePath1.pare         


        
4条回答
  •  情话喂你
    2020-12-19 03:21

    Seems like it, although I would recommend doing a previous manipulation with the directory string instead of calling twice to parent_path():

    std::string directory = "/home/user"; // Try with "/home/user/" too, result is the same
    
    while ((directory.back() == '/') || (directory.back() == '\\')))
        directory.erase(directory.size()-1);    
    
    boost::filesystem::path filePath(directory);
    std::cout << filePath.parent_path() << std::endl; // outputs "/home" 
    

    It is important to note that std::string::back() is a C++11 feature. Should you need to compile with a previous version you will have to change the algorithm a bit.

提交回复
热议问题