读取指定文件夹内所有文件列表

开发 前端
今天分析下利用 scandir 函数获取文件列表。

今天分析下利用 scandir 函数获取文件列表。

函数原型

#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(不包括子目录),经由参数 filter 指定的函数来挑选符合条件的目录结构至参数namelist 数组中,最后再调用参数 compar 指定的函数来排序 namelist 数组中的目录数据。

每次从 dirp 中读取的目录结构后都会传递给 filter 进行过滤,若 filter 返回 0 则不会把该目录结构复制到 namelist 数组中。

若 filter 参数为 NULL,则选择所有目录到 namelist 组中。

scandir() 中会调用 qsort() 来对获取的目录列表进行排序,参数 compar 则为 qsort() 的参数,若是要把目录名称列表按照字母顺序排序则 compar 参数可使用 alphasort()。

返回值 : 返回获取到的目录项的数量。如果发生错误,则返回-1,并设置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);
}

运行结果

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

该结果是按照下标倒序显示的,也可以从下标 0 开始显示,这样就是按照字母排序的了。

使用 filter 参数进行过滤

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

运行结果

#./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
责任编辑:华轩 来源: 今日头条
相关推荐

2020-09-23 08:53:48

父文件夹模块Python

2021-11-17 09:01:23

Python批量合并Python基础

2009-08-12 16:57:28

C#读取文件夹

2021-11-19 08:59:28

Python 批量合并

2017-04-07 11:00:25

Windows 7Windows自动备份

2010-03-25 10:24:32

Python代码

2009-10-27 08:56:22

VB.NET文件夹

2010-12-31 13:35:25

文件夹重定向

2011-08-04 15:36:32

文件夹病毒

2011-03-04 16:37:13

FileZilla

2009-12-03 10:18:32

Linux文件夹执行权限

2015-03-13 13:50:47

Java读取文件夹大小Java读取文件Java读取

2020-05-09 16:25:31

Ubuntu文件夹桌面

2021-08-16 13:34:07

Linux终端删除文件

2023-05-13 17:43:17

Linux文件文件夹

2013-05-28 10:17:02

Windows.old故障恢复

2011-04-11 16:07:13

系统备份

2011-05-23 17:00:29

2010-07-14 21:10:09

VirtualBox

2009-12-09 10:10:08

PHP创建文件夹
点赞
收藏

51CTO技术栈公众号