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

本文介绍了如何用C语言编写一个类似`rm -r`的功能,通过读取指定目录的内容,递归删除文件和子目录。代码中包含`opendir()`用于打开目录,`readdir()`遍历目录项,根据`d_type`判断是文件还是目录,分别调用`remove()`删除文件或递归调用`rmr()`删除子目录,并在最后使用`rmdir()`删除空目录。程序提供了错误处理和正确的使用提示。
摘要由CSDN通过智能技术生成
#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,en
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值