新聞中心
今天分析下利用 scandir 函數(shù)獲取文件列表。

10年積累的成都網(wǎng)站制作、網(wǎng)站建設經(jīng)驗,可以快速應對客戶對網(wǎng)站的新想法和需求。提供各種問題對應的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡服務。我雖然不認識你,你也不認識我。但先建設網(wǎng)站后付款的網(wǎng)站建設流程,更有蘆溪免費網(wǎng)站建設讓你可以放心的選擇與我們合作。
函數(shù)原型
#include
int scandir(const char *restrict dirp,
struct dirent ***restrict namelist,
int (*filter)(const struct dirent *),
int (*compar)(const struct dirent **,const struct dirent **));
scandir() 會掃描目錄 dirp(不包括子目錄),經(jīng)由參數(shù) filter 指定的函數(shù)來挑選符合條件的目錄結構至參數(shù)namelist 數(shù)組中,最后再調(diào)用參數(shù) compar 指定的函數(shù)來排序 namelist 數(shù)組中的目錄數(shù)據(jù)。
每次從 dirp 中讀取的目錄結構后都會傳遞給 filter 進行過濾,若 filter 返回 0 則不會把該目錄結構復制到 namelist 數(shù)組中。
若 filter 參數(shù)為 NULL,則選擇所有目錄到 namelist 組中。
scandir() 中會調(diào)用 qsort() 來對獲取的目錄列表進行排序,參數(shù) compar 則為 qsort() 的參數(shù),若是要把目錄名稱列表按照字母順序排序則 compar 參數(shù)可使用 alphasort()。
返回值 : 返回獲取到的目錄項的數(shù)量。如果發(fā)生錯誤,則返回-1,并設置errno 以指示錯誤。
例子
#include
#include
#include
int main(void)
{
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);
exit(EXIT_SUCCESS);
}
運行結果
#./test
tdir
libc.c
libb.c
liba.c
gg.h
..
.
該結果是按照下標倒序顯示的,也可以從下標 0 開始顯示,這樣就是按照字母排序的了。
使用 filter 參數(shù)進行過濾
#include
#include
#include
int myfilter(const struct dirent *entry)
{
return strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..");
}
int main(void)
{
struct dirent **namelist;
int n;
n = scandir(".", &namelist, myfilter, alphasort);
if (n == -1) {
perror("scandir");
exit(EXIT_FAILURE);
}
while (n--) {
printf("%s\n", namelist[n]->d_name);
free(namelist[n]);
}
free(namelist);
exit(EXIT_SUCCESS);
}
運行結果
#./test
tdir
libc.c
libb.c
liba.c
gg.h
獲取以 lib 開頭的文件
int myfilter(const struct dirent *ent)
{
if(ent->d_type != DT_REG)
return 0;
return (strncmp(ent->d_name, "lib", 3) == 0);
}
運行結果如下:
#./test
libc.c
libb.c
liba.c
分享標題:讀取指定文件夾內(nèi)所有文件列表
本文來源:http://m.5511xx.com/article/codchcd.html


咨詢
建站咨詢
