[英]How to determine if a file is contained by path with Boost Filesystem Library v3?
如何使用 boost 文件系統 v3.0 確定文件是否包含在路徑中?
我看到有一個較小或較大的運算符,但這似乎只是詞法上的。 我看到的最好的方法如下:
有沒有更好的方法來做到這一點?
以下函數應確定文件名是否位於給定目錄中的某個位置,作為直接子目錄或某個子目錄。
bool path_contains_file(path dir, path file)
{
// If dir ends with "/" and isn't the root directory, then the final
// component returned by iterators will include "." and will interfere
// with the std::equal check below, so we strip it before proceeding.
if (dir.filename() == ".")
dir.remove_filename();
// We're also not interested in the file's name.
assert(file.has_filename());
file.remove_filename();
// If dir has more components than file, then file can't possibly
// reside in dir.
auto dir_len = std::distance(dir.begin(), dir.end());
auto file_len = std::distance(file.begin(), file.end());
if (dir_len > file_len)
return false;
// This stops checking when it reaches dir.end(), so it's OK if file
// has more directory components afterward. They won't be checked.
return std::equal(dir.begin(), dir.end(), file.begin());
}
如果您只想檢查該目錄是否是文件的直接父目錄,請改用以下命令:
bool path_directly_contains_file(path dir, path file)
{
if (dir.filename() == ".")
dir.remove_filename();
assert(file.has_filename());
file.remove_filename();
return dir == file;
}
如果您只想在詞法上檢查一個path
是否是另一個path
的前綴,而不必擔心.
, ..
或符號鏈接,你可以使用這個:
bool path_has_prefix(const path & path, const path & prefix)
{
auto pair = std::mismatch(path.begin(), path.end(), prefix.begin(), prefix.end());
return pair.second == prefix.end();
}
請注意,這里使用的std::mismatch
的四參數重載直到 C++14 才被添加。
當然,如果您想要的不僅僅是路徑的嚴格詞法比較,您可以對一個或兩個參數調用lexically_normal()
或canonical()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.