用递归思想扫描指定目录中的特定文件,并计数求出总文件大小。对扫描得到的结果,进行存储到链表中。
#include
#include
#include
#include
#include
#include
#include
#include
#define MAXPATH 32
#define LEN sizeof(struct list)
int count=0; //计量歌曲数
double filesize; //文件总大小
struct list
{
char pathname[1024];
char filename[512];
struct list *next;
};
struct list *head,*p1,*p2;
void scan_dir(char *dir,int depth) //定义目录扫描函数
{
DIR *dp;
struct dirent *entry;
struct stat statbuff;
int l;
if(!(dp=opendir(dir)))
{
//puts("can't open");
return;
}
chdir(dir); //切换到当前目录中去
while((entry=readdir(dp))!=NULL)
{
lstat(entry->d_name,&statbuff); //获取下一级成员属性
if(S_IFDIR&statbuff.st_mode) //判断下一级成员是否是目录
{
if(strcmp(".",entry->d_name)==0||
strcmp("..",entry->d_name)==0)
continue;
//printf("%*s%s/\n",depth,"",entry->d_name);
scan_dir(entry->d_name,depth+4); //调用自身,扫描下一级
}
else
{
l=strlen(entry->d_name);
l-=4;
if(strcmp(entry->d_name+l,".mp3")==0||
strcmp(entry->d_name+l,".MP3")==0)
{ char path_buff[MAXPATH];
getcwd(path_buff, MAXPATH);
p1= malloc(LEN);
strcpy(p1->pathname,path_buff);
strcpy(p1->filename,entry->d_name);
//printf("%s hello %s",p1->pathname,p1->filename);
p1->next=0;
count++;
if(count==1)
head=p2=p1;
else
{ p2->next=p1;
//p2=p2->next;
p2=p1;
//printf("hello");
}
//p2->next=NULL;
//free(p1);free(p2);free(head);
//printf(" %s", path_buff);
//printf("%*s%s\n",depth,"",entry->d_name);
//count++;
int tem;
tem = statbuff.st_size;
filesize+=tem;
}
}
}
chdir(".."); //回到上一级目录
closedir(dp);
}
int print()
{
struct list *temp;
temp=head;
//printf("......here1");
if(head!=NULL)
do {
printf("%s %s\n",temp->pathname,temp->filename);
temp=temp->next;
}while(temp!=NULL);
return ;
}
int main()
{
puts("正在扫描全盘中...");
scan_dir("/home",0);
printf("列表输出如下:\n");
print();
puts("扫描结束");
printf("共计%d首歌曲\n",count);
printf("总大小为%3.2gMB\n",filesize/1024/1024);
return 0;
}
阅读(1049) | 评论(0) | 转发(0) |