您的位置:首页 > 其它

按树的形状列出目录中内容 (程序清单4-7)

2012-03-12 13:51 429 查看
结果:/home/suqin/apuetest





[b]代码:未考虑通用性和文件目录访问权限问题

[/b]

#include"apue.h"
#include<dirent.h>

unsigned int total,reg,dir,chr,blk,fifo,lnk,sock;

int traverse(char *pathname,int dep)
{
DIR *dp;
struct dirent *dirp;

int depth=dep,i;

char tmp[500],tmp2[500];
strcpy(tmp,pathname);

struct stat buf;

if( (dp=opendir(pathname))==NULL)
err_sys("opendir %s error!",tmp);

while( (dirp=readdir(dp))!=NULL)
{
if(strcmp(dirp->d_name,".")==0) continue;
if(strcmp(dirp->d_name,"..")==0) continue;
strcpy(tmp2,tmp);
strcat(tmp2,"/");
strcat(tmp2,dirp->d_name);

for(i=0;i<depth;i++)
printf("|    ");
printf("|----%s\n",dirp->d_name);

if(lstat(tmp2,&buf)<0){
err_ret("lstat error:%s",tmp2);
continue;}

if(S_ISREG(buf.st_mode)) {reg++;continue;}
else if(S_ISCHR(buf.st_mode)) {chr++;continue;}
else if(S_ISBLK(buf.st_mode)) {blk++;continue;}
else if(S_ISFIFO(buf.st_mode)) {fifo++;continue;}
else if(S_ISLNK(buf.st_mode)) {lnk++;continue;}
else if(S_ISSOCK(buf.st_mode)) {sock++;continue;}
else if(S_ISDIR(buf.st_mode))
{
dir++;
traverse(tmp2,depth+1);
continue;
}
else printf("No such file style!\n");

}
return 0;
}

int main(int argc,char *argv[])
{
if(argc!=2) err_sys("argc!=2");
printf("%s\n",argv[1]);
traverse(argv[1],0);

printf("\n reg=%d\n dir=%d\n chr=%d\n blk=%d\n fifo=%d\n sock=%d\n",reg,dir,chr,blk,fifo,sock);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐