列出目录中同名的文件
List files in directory with same name
我有文件夹:C:\Users\Bob\Desktop\SomeFolder.
在文件夹 "SomeFolder" 中,我们有 10 个文件:
abc.txt,abc1.txt,abc2.txt,abc3.txt,abc4.txt,
xyz.txt, xyz1.txt, xyz2.txt, xyz3.txt, xyz4.txt.
现在假设我想显示(列出)名称以 "abc".
开头的所有文件
它应该看起来像这样:
std::string path = "path_to_directory"; //C:\Users\Bob\Desktop\SomeFolder
for (auto & p : fs::directory_iterator(path))
std::cout << p << std::endl;
但我需要某种 "filter"。
只需使用std::string::find
for(auto& p: fs::directory_iterator(tempPath))
{
std::string file_name = p.path().filename();
if ( file_name.find("abc") == 0 )
{
std::cout << file_name <<std::endl;
}
}
对于路径
中的一些 "complicated" 模式,可以像下面那样使用 std::regex
std::regex fileMatcher( tempPath + "/abc.*",
// All files that begins with `abc` in current directory .
std::regex_constants::ECMAScript | std::regex_constants::icase);
for(auto& p: fs::directory_iterator(tempPath))
if (std::regex_match (p.path().c_str() ,fileMatcher ))
{
std::cout << p <<std::endl;
}
可能需要调整 Windows 路径。我没有最新的编译器来检查 windows
编辑代码:
for(auto & p : fs::directory_iterator(path)){
if (regex_match(p , regex("(abc)(.*)"))){
cout <<p<< endl;
}
}
return 0;
它打印以字符串 "abc"
开头的文件名
我有文件夹:C:\Users\Bob\Desktop\SomeFolder.
在文件夹 "SomeFolder" 中,我们有 10 个文件:
abc.txt,abc1.txt,abc2.txt,abc3.txt,abc4.txt,
xyz.txt, xyz1.txt, xyz2.txt, xyz3.txt, xyz4.txt.
现在假设我想显示(列出)名称以 "abc".
开头的所有文件它应该看起来像这样:
std::string path = "path_to_directory"; //C:\Users\Bob\Desktop\SomeFolder
for (auto & p : fs::directory_iterator(path))
std::cout << p << std::endl;
但我需要某种 "filter"。
只需使用std::string::find
for(auto& p: fs::directory_iterator(tempPath))
{
std::string file_name = p.path().filename();
if ( file_name.find("abc") == 0 )
{
std::cout << file_name <<std::endl;
}
}
对于路径
中的一些 "complicated" 模式,可以像下面那样使用std::regex
std::regex fileMatcher( tempPath + "/abc.*",
// All files that begins with `abc` in current directory .
std::regex_constants::ECMAScript | std::regex_constants::icase);
for(auto& p: fs::directory_iterator(tempPath))
if (std::regex_match (p.path().c_str() ,fileMatcher ))
{
std::cout << p <<std::endl;
}
可能需要调整 Windows 路径。我没有最新的编译器来检查 windows
编辑代码:
for(auto & p : fs::directory_iterator(path)){
if (regex_match(p , regex("(abc)(.*)"))){
cout <<p<< endl;
}
}
return 0;
它打印以字符串 "abc"
开头的文件名