#define _XOPEN_SOURCE 1 /*GLIBC要求*/
#define _XOPEN_SOURCE_EXTENDED 1
#include<stdio.h>
#include<ftw.h>
#include<error.h>
#include<limits.h>
#include<unistd.h>
#include<stdlib.h>
#include<getopt.h>
int process(const char* file, /*在nftw()函数中调用的回调函数*/
const struct stat* sb,
int typeflag,struct FTW* ftwbuf);
int usage(char* str) /*出错打印提示函数*/
{
fprintf(stderr,"usage: %s\n",str);
exit(-1);
}
int main(int argc,char** argv)
{
char ch;
int flag = FTW_PHYS,fdnum,i,ft;
char start[1024],finish[1024];
while((ch = getopt(argc,argv,":f")) != -1)/*解析选项*/
{
switch(ch){
case 'f': /*设置FTW_CHDIR标志,该标志表示要打开该目录,要先进入该目录*/
flag |= FTW_CHDIR;break;
default:
usage("invalid option");
}
}
if(optind == argc)
usage(argv[0]);
/*空余文件描述符*/
fdnum = getdtablesize() - 5; /*由于nftw调用如果很深可能会耗尽文件描述符,所以做一些设置*/
getcwd(start,sizeof(start)); /*保存开始时的目录,以后测试用*/
for(i = 2;i < argc;i++)
{
ft = nftw(argv[i],process,fdnum,flag); /*nftw()调用部分*/
if(ft != 0)
perror("nftw"); /*错误提示*/
}
getcwd(finish,sizeof(finish)); /*退出时的目录,测试用*/
if((flag&FTW_CHDIR) != 0)
{
printf("the start file is:%s\n",start);
printf("the finish file is:%s\n",finish);
}
return 0;
}
int process(const char* file,
const struct stat* sb,
int typeflag,struct FTW* ftwbuf)
{
int level = ftwbuf->level; /*为以下打印的时候缩进使用*/
char* name = file + ftwbuf->base; /*name指针指向文件名的第一个字符*/
printf("%*s",level*4," "); /*层次缩进*/
switch(typeflag) /*为相应文件类型设置输出*/
{
case FTW_F:
printf("%s (file)\n",name);break;
case FTW_D:
printf("%s (directory)\n",name);break;
case FTW_DNR:
printf("%s (file can't be read)\n",name);break;
case FTW_SL:
printf("%s (symbolic)\n",name);break;
}
return 0;
}
|