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

结果:/home/suqin/apuetest

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

#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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值