原文:apps.hi.baidu.com/share/detail/32164843

转自:http://zhougaofeng.ixiezi.com/2011/03/29/rm_dir/

好久没更新博客,最近写了一段文件夹遍历的代码,实现删除文件夹下所有文件的功能
贴上来供大家参考
#include <dirent.h>
#include <stdio.h>
#include <string.h>

void rm_dir(char *path);
void usage();

int main(int argv, char *argc[]) {
   if(argv != 2)usage();
   rm_dir(argc[1]);
   return 0;
}

void usage(){
   printf("rm_dir <DirPath>n");
}

void rm_dir(char *path)
{
   struct dirent* ent = NULL;
   DIR *dir;
   static char subdir[1024] = "";

   if(!strcmp(subdir, ""))
       strcpy(subdir, path);
   dir = opendir(path);

   while((ent = readdir(dir))!= NULL){
       if(ent->d_type == 8||ent->d_type == 10){
           char file[1024] = "";
           strcpy(file, subdir);
           strcat(file, "/");
           strcat(file, ent->d_name);
           printf("List file %s\n", ent->d_name);
           remove(file);
       }
       else {
           if(!strcmp(ent->d_name, "..") ||!strcmp(ent->d_name, "."))
               continue;
           strcat(subdir, "/");
           strcat(subdir, ent->d_name);
           printf("Sub dir %s %d dirpath = %s type = %d\n", ent->d_name, ent->d_reclen, subdir, ent->d_type);
           rm_dir(subdir);
           remove(subdir);
           subdir[(int)(strlen(subdir)- strlen(ent->d_name)- 1)] = '\0';
           printf("Return %s\n", ent->d_name, ent->d_reclen);
       }
   }
   closedir(dir);
}

原创文章,转载请注明,谢谢合作~~~

posted on 2011-10-11 11:02  hotty  阅读(601)  评论(1)    收藏  举报