偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

讀取指定文件夾內(nèi)所有文件列表

開發(fā) 前端
今天分析下利用 scandir 函數(shù)獲取文件列表。

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

函數(shù)原型

#include <dirent.h>

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ù)來挑選符合條件的目錄結(jié)構(gòu)至參數(shù)namelist 數(shù)組中,最后再調(diào)用參數(shù) compar 指定的函數(shù)來排序 namelist 數(shù)組中的目錄數(shù)據(jù)。

每次從 dirp 中讀取的目錄結(jié)構(gòu)后都會傳遞給 filter 進行過濾,若 filter 返回 0 則不會把該目錄結(jié)構(gòu)復制到 namelist 數(shù)組中。

若 filter 參數(shù)為 NULL,則選擇所有目錄到 namelist 組中。

scandir() 中會調(diào)用 qsort() 來對獲取的目錄列表進行排序,參數(shù) compar 則為 qsort() 的參數(shù),若是要把目錄名稱列表按照字母順序排序則 compar 參數(shù)可使用 alphasort()。

返回值 : 返回獲取到的目錄項的數(shù)量。如果發(fā)生錯誤,則返回-1,并設(shè)置errno 以指示錯誤。

例子

#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>

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);
}

運行結(jié)果

#./test
tdir
libc.c
libb.c
liba.c
gg.h
..
.

該結(jié)果是按照下標倒序顯示的,也可以從下標 0 開始顯示,這樣就是按照字母排序的了。

使用 filter 參數(shù)進行過濾

#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>

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);
}

運行結(jié)果

#./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);
}

運行結(jié)果如下:

#./test
libc.c
libb.c
liba.c
責任編輯:華軒 來源: 今日頭條
相關(guān)推薦

2020-09-23 08:53:48

父文件夾模塊Python

2021-11-17 09:01:23

Python批量合并Python基礎(chǔ)

2009-08-12 16:57:28

C#讀取文件夾

2021-11-19 08:59:28

Python 批量合并

2017-04-07 11:00:25

Windows 7Windows自動備份

2009-10-27 08:56:22

VB.NET文件夾

2010-03-25 10:24:32

Python代碼

2010-12-31 13:35:25

文件夾重定向

2009-12-03 10:18:32

Linux文件夾執(zhí)行權(quán)限

2024-12-06 15:11:34

Python文件夾目錄

2020-05-09 16:25:31

Ubuntu文件夾桌面

2015-03-13 13:50:47

Java讀取文件夾大小Java讀取文件Java讀取

2011-08-04 15:36:32

文件夾病毒

2011-03-04 16:37:13

FileZilla

2010-03-05 16:54:47

2009-12-09 10:10:08

PHP創(chuàng)建文件夾

2010-07-14 21:10:09

VirtualBox

2021-04-01 16:36:07

macOS文件夾磁盤

2023-05-13 17:43:17

Linux文件文件夾

2021-08-16 13:34:07

Linux終端刪除文件
點贊
收藏

51CTO技術(shù)棧公眾號