Posted on 2013-01-02 11:48
鑫龍 閱讀(3212)
評論(0) 編輯 收藏 引用 所屬分類:
linux編程
首先看一下man的scandir 接口定義
int scandir(const char *dir, struct dirent ***namelist, int(*filter)(const struct dirent *), int(*compar)(const struct dirent **, const struct dirent **));
|
,從定義來看就不是一個簡單的函數,形參里,出現一個三級指針,二個函數指針。它的功能是,掃描名字為dir的目錄,把滿足filter函數的過濾條件(即filter執行為非0值)的目錄項加入到一維指針數組namelist.數組的總長度為返回值n,如果compar不為空,則最終輸出結果還要調用qsort來對數組進行排序后再輸出。
從scandir的演示代碼,我們可以推算出namelist是一個指向一維指針數組的指針。(一維指針數組等同于 struct dirent ** namelist,這里寫在三級指針是因為要從函數里改變namelist的值,必須再多做一級)原因可以參考我的函數傳值類型的說明。
以下是一個簡單掃描 /usr/lib,并且把所有以lib打頭的文件掃描到namelist數組的測試程序,這是參考scandir 提供的樣例來修改,alphasort是做原始的ASCII碼值比較進行排序的
可以看到namelist是完全動態分配的,不僅數組本身是動態分配,而且數組項指向的空間也是動態分配的。
#include <sys/types.h> #include <dirent.h>
#include <sys/stat.h> #include <unistd.h>
#include <stdio.h> #include <errno.h> #include <string.h> #include <stdlib.h>
//掃描所有的lib打頭的文件
int filter_fn(const struct dirent * ent) { if(ent->d_type != DT_REG) return 0; return (strncmp(ent->d_name,"lib",3) == 0); }
void scan_lib(char * dir_name) { int n; struct dirent **namelist; // struct dirent * namelist[];
n = scandir(dir_name, &namelist, filter_fn, alphasort); if (n < 0) perror("scandir"); else { while(n--) { printf("%s\n", namelist[n]->d_name); free(namelist[n]); } free(namelist); } }
int main(int argc ,char * argv[]) { scan_lib("/usr/lib"); }
|