[英]How to check a file is contained in a folder with C++?
假設文件和文件夾確實存在,我想要一個函數來檢查文件是否包含在文件夾中。
例如: /a/b
包含/a/b/c/de
, /a/b
包含/a/b/cd
, /a/b
不包含/a/b/../c/de
。
我現在得到的是規范化路徑,然后比較前綴部分。 有沒有一些干凈簡單的方法來做到這一點?
我會假設文件路徑是這樣的:C:\\Program Files\\Important\\data\\app.exe 而文件夾路徑是這樣的:C:\\Program Files 因此你可能想嘗試這個代碼:
#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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.