標籤:
scandir函數詳解
2009-10-30 10:51
scandir函數:讀取特定的目錄資料
表標頭檔:#include <dirent.h>
定義函數:int scandir(const char *dir, struct dirent **namelist, nt (*select) (const struct dirent *), nt
(*compar) (const struct dirent **, const struct dirent**));
函數說明:
scandir()會掃描參數dir指定的目錄檔案,經由參數select指定的函數來挑選目錄結構至參數namelist數組中,最後再調用
參數compar指定的函數來排序namelist 數組中的目錄資料。每次從目錄檔案中讀取一個目錄結構後便將此結構傳給參數select所指的
函數, select函數若不想要將此目錄結構複製到namelist數組就返回0,若select為空白指標則代表選擇所有的目錄結構。scandir()會
調用 qsort()來排序資料,參數compar則為qsort()的參數,若是要排列目錄名稱字母則可使用alphasort(). 結構dirent定義請參考
readdir()
傳回值 :成功則返回複製到namelist數組中的資料結構數目,有錯誤發生則返回-1
錯誤碼:ENOMEM 核心記憶體不足
Example
#include <dirent.h>
main()
{
struct dirent **namelist;
int n;
n = scandir(".", &namelist, 0, alphasort);
if (n < 0)
perror("scandir");
else
{
while(n--)
{
printf("%s\n", namelist[n]->d_name);
free(namelist[n]);
}
free(namelist);
}
}
轉自:http://blog.sina.com.cn/s/blog_6a113b0a0100uzb3.html
scandir函數詳解