讀取目錄下的檔案列表
定義
#include <dirent.h>
int scandir(const char *dirp, struct dirent ***namelist,
int (*filter)(const struct dirent *),
int (*compar)(const struct dirent **, const struct dirent **));
int alphasort(const struct dirent **a, const struct dirent **b);
int versionsort(const struct dirent **a, const struct dirent **b);
基本用法
struct dirent **namelist;
int i, j;
if((j = scandir(".", &namelist, NULL, alphasort))) {
for (i = 0; i < j; i++) {
if(!strcmp(namelist[i]->d_name, ".") || !strcmp(namelist[i]->d_name, "..")) {
free(namelist[i]);
continue;
}
printf("%s\n", namelist[i]->d_name);
free(namelist[i]);
}
free(namelist);
}
排序方法:alphasort、versionsort
filter 方法
可在上述 scandir 的 NULL 位置代入
int filter(const struct dirent *entry) {
return strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..");
}
自訂排序方法
int compar(const struct dirent **_a, const struct dirent **_b) {
struct dirent *a = *_a;
struct dirent *b = *_b;
return strcmp(a->d_name, b->d_name);
}
沒有留言:
張貼留言