Следующая функция должна определять, находится ли имя файла где-то внутри данного каталога, либо как прямой, либо в каком-либо подкаталоге.
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;
}
Вы также можете быть заинтересованы в the discussion about what "the same" means отношении operator==
для путей.
Эта функция должна жить в пределах Boost. Я предполагаю, что это ваши авторские права, тогда я могу спросить вас, какие условия использования? Общественное достояние, пожалуйста? – vinipsmaker
@ Vinipsmaker, условия использования для моего кода такие же, как и условия использования всего на всей сети Stack Exchange, которые связаны с нижней частью каждой страницы: «Пользовательские взносы, лицензированные под CC By-SA 3.0 с атрибуцией обязательный." –
Я считаю, что эта функция имеет дефект, препятствующий безопасности, рассмотрим '' path_contains_file ("folder1/folder2", "folder1/folder2 /../../ secretFolder/sectedFile.txt") '' Так что если вы используете его для проверки доступа , они могут ошибочно пройти. Использование '' filesystem :: canonical'' исправило бы это, но только для существующих файлов! – PhilLab