目录扫描

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void printdir(char *dir,int depth)
{
    DIR *dp;
    struct dirent *entry;
    struct stat statbuf;
    if((dp=opendir(dir))==NULL)
    {
        fprintf(stderr,"cannot open directory:%s\n",dir);
         return;
    }
    chdir(dir);
    while((entry=readdir(dp))!=NULL)
    {
        lstat(entry->d_name,&statbuf);
        if(S_ISDIR(statbuf.st_mode))
        {
            if((strcmp(".",entry->d_name)==0)||(strcmp("..",entry->d_name)==0))
continue;
            printf("%d  %s\n",depth,entry->d_name);


            printdir(entry->d_name,depth+=1);
         }
        else
            printf("%d  %s\n",depth,entry->d_name);

    }
    chdir("..");
    closedir(dp);
}
int main(int argc,char * argv[])
{
     printf("doing\n");
     char *topdir=".";
     if(argc>1)
         topdir=argv[1];
    printdir("/home/cqh/Downloads",0);
    printf("done\n");
   exit(0);
}
posted @ 2015-09-22 18:11  陈泉宏  阅读(216)  评论(0编辑  收藏  举报