您的位置:首页 > 编程语言 > C语言/C++

C语言实现ls命令

2015-08-26 20:28 1141 查看
#include<stdio.h>
#include<unistd.h>
#include<sys/stat.h>
#include<dirent.h>
#include<string.h>
#include<sys/types.h>
void list_func(char*path,int depth)
{
DIR*pDirHandle= opendir(path);
struct dirent * dent ;
struct stat  fstat ;
if(pDirHandle==NULL)
{
printf("OpenDir %s  Error!\n",path);
exit(0);
}
chdir(path);
while((dent=readdir(pDirHandle))!=NULL)
{
//error then return -1
lstat(dent->d_name,&fstat);
if(S_ISDIR(fstat.st_mode))
{
//remove director . and ..
if(strcmp(".",dent->d_name)==0||
strcmp("..",dent->d_name)==0 )
continue ;
printf("%*s%s/\n",depth,"",dent->d_name) ;
list_func(dent->d_name,depth+4) ;
}else
printf("%*s%s\n",depth,"",dent->d_name);
}
chdir("..");
closedir(pDirHandle);
}
int main(int argc,char**argv)
{     char *pDirPath;
if(argc==1)
{
pDirPath = ".";

}
else{
pDirPath=argv[1];
}
int depath=0;
printf("List Begin:\n");
list_func(pDirPath,depath) ;
printf("List End.\n");
return 0 ;
}

这里用到的库文件,和opendir等函数,和stat结构体等。需要看源码或查资料理解。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: