如何检查文件是否包含在 C++ 的文件夹中?

How to check a file is contained in a folder with C++?

假设文件和文件夹确实存在,我想要一个函数来检查文件是否包含在文件夹中。

例如:/a/b包含/a/b/c/d.e/a/b包含/a/b/c.d/a/b不包含/a/b/../c/d.e

我现在得到的是路径归一化,然后比较前缀部分。有没有一些干净简单的方法来做到这一点?

我假设文件路径是这样的: C:\程序Files\Important\data\app.exe 而文件夹路径是这样的: C:\程序文件 因此,您可能想试试这个代码:

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string filePath, folderPath;
    cout << "Insert the full file path along with its name" << endl;
    getline(cin,filePath); //using getline since a path can have spaces
    cout << "Insert the full file folder path" << endl;
    getline(cin,folderPath);
    if(filePath.find(folderPath) != string::npos)
    {
        cout << "yes";
    }
    else
    {
        cout << "yes";
    }
    return 0;
}

只有从 C++17 开始才有 std::filesystem API 具有这种能力。
对于早期的 C++ 版本,您必须回退到 boost 或系统特定库。

遗憾的是 std::filesystem::path 没有直接方法,但这应该可以完成工作:

using std::filesystem::path;

path normalized_trimed(const path& p)
{
    auto r = p.lexically_normal();
    if (r.has_filename()) return r;
    return r.parent_path();
}

bool is_subpath_of(const path& base, const path& sub)
{
    auto b = normalized_trimed(base);
    auto s = normalized_trimed(sub).parent_path();
    auto m = std::mismatch(b.begin(), b.end(), 
                           s.begin(), s.end());

    return m.first == b.end();
}

Live demo