linux c实现递归删除命令 rm -r

来源:互联网 发布:td网络健康度指标包括 编辑:程序博客网 时间:2024/05/18 05:01
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <libgen.h>
#include <string.h>
void rmr(char* path)
{
  DIR* dir = opendir(path);
  if(dir == NULL)
   perror("opendir"),exit(-1);
  struct dirent* ent;
  char buf[256];
  while((ent=readdir(dir)))
  {
    if(ent->d_type == 4)
    {
      if(strcmp(ent->d_name,".")==0||strcmp(ent->d_name,"..")==0)
      continue;
      sprintf(buf,"%s/%s",path,ent->d_name);
      
      rmr(buf);
     
    }
    if(ent->d_type == 8)
    {
      sprintf(buf,"%s/%s",path,ent->d_name);
      if(remove(buf)!=0) perror("remove"),exit(-1);
    }
  }
  if(rmdir(path)!=0) perror("rmdir"),exit(-1);
}
int main(int argc,char* argv[])
{
  if(argc != 2)
  {
    printf("Usage:%s directory name",basename(argv[0]));
    exit(-1);
  }
 
  rmr(argv[1]);
  printf("rm -r %s success.\n",argv[1]);
  return 0;
}
0 0
原创粉丝点击