使用scandir 显示目录下的文件
#include <stdio.h>
#include <stdlib.h> /* free() */
#include <dirent.h>
int main(void) {
struct dirent **filelist = {0};
char *directory = ".";
int fcount = -1;
int i = 0;
fcount = scandir(directory, &filelist, 0, alphasort);
if(fcount < 0) {
perror(directory);
return 1;
}
for(i = 0; i < fcount; i++) {
printf("%02d: %s/n", i, filelist[i]->d_name);
free(filelist[i]);
}
free(filelist);
return 0;
}
使用filter
#include <stdio.h>
#include <stdlib.h> /* free() */
#include <dirent.h>
#include <fnmatch.h>
int filter(const struct dirent *entry)
{
if (fnmatch("ywtest*", entry->d_name, FNM_PATHNAME|FNM_PERIOD) == 0)
{
printf("file is %s/n", entry->d_name);
return 1;
}
else
{
return 0;
}
}
int main(void) {
struct dirent **filelist = {0};
char *directory = ".";
int fcount = -1;
int i = 0;
fcount = scandir(directory, &filelist, filter, alphasort);
printf("coutn is %d/n", fcount);
if(fcount < 0) {
perror(directory);
return 1;
}
for(i = 0; i < fcount; i++) {
printf("%02d: %s/n", i, filelist[i]->d_name);
free(filelist[i]);
}
free(filelist);
return 0;
}
用了filter函数,就可以过滤掉不需要的文件。
使用fnmatch显示匹配的文件
#include <locale.h>
#include <fnmatch.h>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main(int argc, char *argv[] )
{
char *pattern;
DIR *dir;
struct dirent *entry;
int ret;
/*setlocale(LC_ALL, "zh_CN.UTF-8");*/
if(argc != 3)
{
printf("Usage: a.out pattern directory/n");
return 0;
}
dir = opendir(argv[2]);
pattern = argv[1];
printf("dir %s,pattern %s/n", argv[2], pattern);
if(dir != NULL){
while( (entry = readdir(dir)) != NULL){
ret = fnmatch(pattern, entry->d_name, FNM_PATHNAME|FNM_PERIOD);
if(ret == 0){
printf("%s/n", entry->d_name);
}else if(ret == FNM_NOMATCH){
continue ;
}else{
printf("error file=%s/n", entry->d_name);
}
}
closedir(dir);
}
}