我想分享一些东西,并感谢您的阅读材料。玩弄一下这个函数来理解它。你可能会喜欢。 e 代表扩展,p 代表路径,s 代表路径分隔符。
如果传递的路径没有结束分隔符,则分隔符将附加到路径。对于扩展名,如果输入了一个空字符串,那么该函数将返回其名称中没有扩展名的任何文件。如果输入了单个星号,则将返回目录中的所有文件。如果 e 长度大于 0 但不是单个 *,则如果 e 在零位置不包含点,则将在 e 前面添加一个点。
对于返回值。如果返回零长度映射,则没有找到任何内容,但目录打开正常。如果返回值中索引 999 可用,但映射大小仅为 1,则表示打开目录路径时出现问题。
请注意,为了提高效率,此函数可以拆分为 3 个较小的函数。最重要的是,您可以创建一个调用函数,该函数将根据输入检测将要调用的函数。为什么这样更有效率?说如果您要抓取文件中的所有内容,那么执行该方法时,为抓取所有文件而构建的子函数只会抓取所有文件,并且每次找到文件时都不需要评估任何其他不必要的条件。
这也适用于您抓取没有扩展名的文件时。为此目的的特定构建函数只会在找到的对象是文件时评估天气,然后判断文件名中是否包含点。
如果您只读取文件不多的目录,则节省可能不会太多。但是,如果您正在读取大量目录,或者该目录有几十万个文件,则可能会节省大量资金。
#include <stdio.h>
#include <sys/stat.h>
#include <iostream>
#include <dirent.h>
#include <map>
std::map<int, std::string> getFile(std::string p, std::string e = "", unsigned char s = '/'){
if ( p.size() > 0 ){
if (p.back() != s) p += s;
}
if ( e.size() > 0 ){
if ( e.at(0) != '.' && !(e.size() == 1 && e.at(0) == '*') ) e = "." + e;
}
DIR *dir;
struct dirent *ent;
struct stat sb;
std::map<int, std::string> r = {{999, "FAILED"}};
std::string temp;
int f = 0;
bool fd;
if ( (dir = opendir(p.c_str())) != NULL ){
r.erase (999);
while ((ent = readdir (dir)) != NULL){
temp = ent->d_name;
fd = temp.find(".") != std::string::npos? true : false;
temp = p + temp;
if (stat(temp.c_str(), &sb) == 0 && S_ISREG(sb.st_mode)){
if ( e.size() == 1 && e.at(0) == '*' ){
r[f] = temp;
f++;
} else {
if (e.size() == 0){
if ( fd == false ){
r[f] = temp;
f++;
}
continue;
}
if (e.size() > temp.size()) continue;
if ( temp.substr(temp.size() - e.size()) == e ){
r[f] = temp;
f++;
}
}
}
}
closedir(dir);
return r;
} else {
return r;
}
}
void printMap(auto &m){
for (const auto &p : m) {
std::cout << "m[" << p.first << "] = " << p.second << std::endl;
}
}
int main(){
std::map<int, std::string> k = getFile("./", "");
printMap(k);
return 0;
}