scandir函数
函数原型:
#include <dirent.h>
int scandir(const char *dirp, struct dirent ***namelist,
int (*filter)(const struct dirent *),
int (*compar)(const struct dirent **, const struct dirent **));
功能:
1. scandir函数扫描文件夹dirp(制定的文件夹路径),
2. 对扫描到的每个词条,调用filter函数,调用后函数返回非0,就将词条存储在通过malloc(3)分配的string中。
3. 对2中的存储的词条用使用了比较函数 compar()的排序函数qsort(3),并将排序结果保存在namelist中
4. 如果filter是NULL则所有的词条都被选择不进行任何筛选。
5. 以下两个函数常用于compar()。
int alphasort(const struct dirent **a, const struct dirent **b); int versionsort(const struct dirent **a, const struct dirent **b);
下面介绍alphasort 和 versionsort
alphasort 按照字符串的大小排序。
实验代码:
#include <iostream> #include <string.h> #include <stdio.h> #include <stdint.h> #include <dirent.h> #include <stdlib.h> using namespace std; int main() { struct dirent **namelist; int n; n = scandir(".", &namelist, NULL, alphasort); if(n == -1) { perror("scandir"); exit(EXIT_FAILURE); } while(n--) { printf("%s\n", namelist[n]->d_name); free(namelist[n]); } free(namelist); return 0; }
当前文件夹下的子文件夹:
➜ t6 ls
1 2 3 a aa b c test test1.cc
运行结果:
test1.cc test c b aa a 3 2 1 .. .
可见这个文件夹扫描函数将文件夹下的多有文件都扫描出来了。
那如果第三个参数非空呢?
实验代码:
#include <iostream> #include <string.h> #include <stdio.h> #include <stdint.h> #include <dirent.h> #include <stdlib.h> using namespace std; int t_numOpenedFiles = 0; int fdDirFilter(const struct dirent* d) { if(::isdigit(d->d_name[0])) //文件名的第一个字符是否是数字 { ++t_numOpenedFiles; } return 0; } int main() { struct dirent **namelist; int n; n = scandir(".", &namelist, fdDirFilter, alphasort); if(n == -1) { perror("scandir"); exit(EXIT_FAILURE); } while(n--) { printf("%s\n", namelist[n]->d_name); free(namelist[n]); } free(namelist); cout<<t_numOpenedFiles<<endl; return 0; }
输出结果:
➜ t6 ./test
3
一个文件夹都没输出,输出了一个3,原因是当前文件或文件夹以数字开头的有三个。

浙公网安备 33010602011771号