Linux下快速获取文件名的编程方法
1. 通过Linux 命令行的方法进行过滤,并重定向到一个临时文件中,之后通过编程读取每一行的内容即可;
2. 通过 scandir 函数进行处理,使用的是快速排序的方法。
1. candir的函数定义
#include <dirent.h>
int scandir( const char *dirp,
struct dirent ***namelist,
int (*filter)(const struct dirent *),
int (*compar)(const struct dirent **, const struct dirent **));
对上述函数的参数进行解释:
- dirp: 需要获取所有文件名的目录;
- namelist: 保存过滤后的全部文件名;
- filter: 过滤函数,为NULL时,输入全部,否则将用filter进行过滤输出;
- compar:表示用来快速排序的参数,可以进行按字母排序的方式;
- 返回值:过滤后符合的总数。
2. candir的使用
#include <dirent.h>
int alphasort(const struct dirent **a, const struct dirent **b);
int versionsort(const struct dirent **a, const struct dirent **b);
scandir 函数中的 compar 参数使用上述的两个函数作为参数,alphasort 表示使用字母来进行快速排序,versionsort 表示使用版本来进行排序。一般情况下,使用 alphasort 函数即可完成很多需要排序的工作。
3. 实例
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
int wav_filter(const struct dirent *dir)
{
const char *name = dir->d_name;
int len = strlen(name);
if(4 > len)
{
return 0;
}
else
{
name = name + (len - 4);
if(0 == strncasecmp(name, ".wav", 4))
{
return 1;
}
else
{
return 0;
}
}
}
int main(int argc, char const *argv[])
{
struct dirent **entry_list;
int count = -1;
int i;
count = scandir("./files", &entry_list, wav_filter, alphasort);
if(count < 0)
{
printf("\nscandir failed\n");
return -1;
}
printf("count = %d\n", count);
for(i = 0; i < count; i++)
{
struct dirent *entry;
entry = entry_list[i];
printf("%s --- %d \n", entry->d_name, entry->d_type);
free(entry);
}
free(entry_list);
return 0;
}
例子中过滤了文件的类型必须是已".wav"作为后缀的文件,为了能够说明该函数进行数据的获取的快速方标,作者使用shell文件进行了创建3000和文件,其中1900个为wav后缀格式的文件,剩余的为txt后缀文件,并且已时间作为前缀。 如下:
#!/bin/bash
cnt=0
rm ./files -rf
mkdir -p ./files
while [ $cnt -lt 3000 ]
do
let cnt=$cnt+1
times=`date +%Y%m%d%H%M%S%05N`
if [ $cnt -lt 1900 ];then
touch ./files/$times.wav
else
touch ./files/$times.txt
fi
done
3. 显示结果:
编译: gcc test.c -o test
运行: time ./test
实际上的时间显示为0.11秒,也即是说是110毫秒就可以获取到1900个特定格式的文件。