【问题标题】:How to check a file is contained in a folder with C++?如何检查文件是否包含在使用 C++ 的文件夹中?
【发布时间】:2020-06-17 04:52:40
【问题描述】:

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

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

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

【问题讨论】:

标签: c++ regex string path filesystems


【解决方案1】:

只有从 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

【讨论】:

    【解决方案2】:

    我会假设文件路径是这样的: C:\Program 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-10-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 2015-09-14
      • 2014-05-10
      • 1970-01-01
      相关资源
      最近更新 更多