2013-03-21 33 views
10

如何確定文件是否包含在具有boost文件系統v3的路徑中。如何通過升壓文件系統v3確定文件是否包含在路徑中

我看到有一個較小或較大的運算符,但這似乎只是詞法。 我看到的最好的方法是如下:

  • 取文件和路徑
  • 的兩個絕對路徑刪除文件的最後部分,看看它是否等於路徑(如果它確實它包含)

有沒有更好的方法來做到這一點?

回答

12

以下函數應該確定文件名是否位於給定目錄中的某個位置,既可以是直接子目錄,也可以是某個子目錄。

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

您還可能有關於operator==的路徑感興趣the discussion about what "the same" means

+0

這個函數應該存在於Boost中。我認爲這是你的版權,那麼我可以問你什麼是使用條款?請問公共領域? – vinipsmaker 2014-08-18 18:40:45

+0

@Vinipsmaker,我的代碼的使用條款與整個Stack Exchange網絡上從每頁底部鏈接的所有內容的使用條款相同:「CC By-SA 3.0中許可的用戶貢獻,帶有署名需要。」 – 2014-08-18 19:03:03

+1

我相信這個函數有一個安全漏洞,考慮''path_contains_file(「folder1/folder2」,「folder1/folder2 /../../ secretFolder/sectedFile.txt」)''所以如果你使用它進行訪問檢查,他們可能會錯誤地通過。使用''filesystem :: canonical''可以解決這個問題,但只適用於現有的文件! – PhilLab 2016-12-19 09:19:42

相關問題