#include<unistd.h>
#include<stdio.h>
#include<string.h>
#include<sys/stat.h>
#include<dirent.h>
//获得目录的函数,第一个参数是根目录 ,第二个参数是挖掘深度
void printdir(char*dir,int mark)
{
DIR *dp=NULL;
struct dirent *entry=NULL;
struct stat statbuf={0};
if((dp=opendir(dir))==NULL)
{
printf("i am sorry can not open the dir%s",dir);
return;
}
chdir(dir);//chdir函数是做什么的?,改变当前目录成为指定目录
while((entry=readdir(dp))!=NULL)
{
lstat(entry->d_name,&statbuf);
if(S_ISDIR(statbuf.st_mode))
{
//如果是目录文件的话i,看看是不是自己或者父目录
if(strcmp(".",entry->d_name)==0)
{
continue;
}
if(strcmp("..",entry->d_name)==0)
{
continue;
}
//如果不是打印出当前文件名称
printf("文件夹:%s\n",entry->d_name);
if(mark==1)
printdir(entry->d_name,3);
}
else
{
printf("文件名称:%s\n",entry->d_name);
}
}
chdir("..");
closedir(dp);
}
int main(int argc,char* argv[])
{
char* topdir,pwd[2]=".";
if(argc!=3)
{
printf("Invalid Arguments\n");
return;
}
else
topdir=argv[1];
if(strcmp(argv[2],"s")==0)
printdir(topdir,1);
else
printdir(topdir,0);
}
本来是想printdir的第二个参数是bool类型的,可是gcc编译器没有定义,也就只能退而求其次,使用int类型的了,如果有参数s则遍历时使用递归遍历