To remove the trailing separator from a path that is to a directory, so far this is working for me:
/**
* Creates lexically normal (removes extra path separators and dots) directory
* path without trailing path separator slash(es)
* @param dir_path - directory path to normalize
*/
void normalize_dir_path(boost::filesystem::path& dir_path) {
// @HACK - append non-existing file to path so that we may later resolve
// normalized directory path using parent_path()
dir_path /= "FILE.TXT";
// Remove unneeded dots and slashes
dir_path = dir_path.lexically_normal();
// Remove trailing slash from original path!
dir_path = dir_path.parent_path();
}
The above answer is similar to OP's original posted workaround (add '/'
) in combination with Wurmloch's comment about using lexically_normal()
. One advantage is that only the documented methods from boost::filesystem
are used. One possible disadvantage is that caller must be confident the input argument dir_path
is intended to be a directory and not a regular file.
Using the normalize_dir_path(...)
method to answer OP's question:
boost::filesystem::path filePath1 = "/home/user/";
normalize_dir_path(filePath1); // filePath1 is now "/home/user"
cout << filePath1.parent_path() << endl; // outputs "/home"
boost::filesystem::path filePath2 = "/home/user";
normalize_dir_path(filePath2); // filePath2 is now "/home/user"
cout << filePath2.parent_path() << endl; // outputs "/home"
boost::filesystem::path filePath3 = "/home/user/.";
normalize_dir_path(filePath3); // filePath3 is now "/home/user"
cout << filePath3.parent_path() << endl; // outputs "/home"
Update
Just realized that boost::filesystem::path::lexically_normal()
is only available on BOOST version >= 1_60_0. For earlier versions, there appears to be a deprecated function available by default boost::filesystem::path::normalize()
(as long as BOOST_FILESYSTEM_NO_DEPRECATED
is not defined). So, my current normalize directory path method is along the lines:
#include <boost/version.hpp>
void normalize_dir_path(boost::filesystem::path& dir_path) {
// @HACK - append non-existing file to path so that we may later resolve
// normalized directory path using parent_path()
dir_path /= "FILE.TXT";
// Remove unneeded dots and slashes
#if BOOST_VERSION >= 106000
dir_path = dir_path.lexically_normal();
#else
dir_path.normalize();
#endif
// Remove trailing slash from original path!
dir_path = dir_path.parent_path();
}