23,216
社区成员




//所要达到的目的: 我想使用scandir来实现筛选出 .c类型的文件
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
//自定义筛选回调函数
int myfilter(const struct dirent *filename)
{
char buf[20];
memset(buf,0,20);
int len=strlen(buf);
memcpy(buf,filename->d_name,len);
if(memcmp(filename->d_name,".c",10)==0) //这里比对方法好像不对?
{
return 0;
}
else
return 1;
}
int main()
{
int n;
struct dirent **namelist;
n=scandir("./",&namelist,
myfilter,alphasort);
while(n--)
{
printf("%s\n",namelist[n]->d_name);
}
return 0;
}
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void walk(const char *name)
{
int i, n;
size_t len;
struct dirent **list;
char *path;
n = scandir(name, &list, NULL, alphasort);
for (i = 0; i < n; i++) {
/* skip . && .. */
if (!strcmp(".", list[i]->d_name)
|| !strcmp("..", list[i]->d_name))
continue;
/* is a dir, recursive */
if (DT_DIR == list[i]->d_type) {
path = malloc(strlen(name) + 1 + strlen(list[i]->d_name) + 1);
sprintf(path, "%s/%s", name, list[i]->d_name);
walk(path);
free(path);
}
/* *.c */
len = strlen(list[i]->d_name);
if (len >= 2
&& list[i]->d_name[len - 2] == '.'
&& list[i]->d_name[len - 1] == 'c')
printf("%s/%s\n", name, list[i]->d_name);
}
free(list);
}
int main(void)
{
walk("/usr/src/sbin");
return 0;
}
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
int isDir(char *filename) //判断是否是目录
{
struct stat info;
stat(filename,&info);
if(S_ISDIR(info.st_mode))
return 1;
return 0;
}
int myfilter(const struct dirent *filename) //文件筛选器
{
size_t len;
len = strlen(filename->d_name);
if (len >= 2
&& filename->d_name[len - 2] == '.'
&& filename->d_name[len - 1] == 'c')
return 1;
return 0;
}
void show(char *filename,int(*myfilter)(const struct dirent *)) //显示文件名列表
{
int n;
struct dirent **namelist;
n=scandir(filename,&namelist,
myfilter,alphasort);
while(n--)
{
printf("%s\n",namelist[n]->d_name);
filename=strcat("./",namelist[n]->d_name); //使用递归子目录
if(isDir(filename))
{
show(filename,myfilter);
}
}
}
int main()
{
char *filename="./";
show(filename,myfilter);
return 0;
}