d_name)com/2011/03/29/rm_dir/ staticcharsubdir[1024]="" else{ dir=opendir(path) ") subdir[(int)(" />

您的位置:首页 > 家用电器 > 厨房电器 > C实现遍历文件夹及删除其内容

C实现遍历文件夹及删除其内容

luyued 发布于 2011-04-11 11:28   浏览 N 次  

  转自:http://zhougaofeng.ixiezi.com/2011/03/29/rm_dir/ 好久没更新博客,最近写了一段文件夹遍历的代码,实现删除文件夹下所有文件的功能

  贴上来供大家参考

  #include

  #include

  #include

  voidrm_dir(char*path);

  voidusage(); intmain(intargv,char*argc[]){

  if(argv!=2)usage();

  rm_dir(argc[1]);

  return0;

  } voidusage(){

  printf("rm_dir n");

  }

  voidrm_dir(char*path)

  {

  structdirent*ent=NULL;

  DIR*dir;

  staticcharsubdir[1024]=""; if(!strcmp(subdir,""))

  strcpy(subdir,path);

  dir=opendir(path); while((ent=readdir(dir))!=NULL){

  if(ent->d_type==8||ent->d_type==10){

  charfile[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);

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

广告赞助商