unix下删除目录的小程序

目的:


目前unix下没有直接删除目录的API函数:rmdir删除目录的话,前提是目录必须为空;而remove和unlink都不能删除目录。

由于工作中需要用到删除目录的功能,在此封装一个函数删除文件或者目录。


基本思想:

递归遍历每一个目录,是普通文件则remove删除,是目录文件,调用rmdir删除;

传入参数:文件或者目录的全路径

返回值:0表示成功,负数表示失败


初步测试没有问题,如有bug,请自行修改

#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>

int DelFile(const char* pathname);
int main()
{
   int ret=0;
   ret = unlink("/home/myhome/caotest");   //直接unlink,删不掉
   printf("unlink return %d\n",ret);
   printf("ERROR:%s\n",strerror(errno));
   
   DelFile("/home/myhome/caotest");

   return 0;
}


int DelFile(const char* pathname)
{
	struct stat statbuf;
	struct dirent *dirp;
	DIR *dp;
	int ret;

	if(lstat(pathname,&statbuf) < 0)
	{
		return -1;
	}
	if(S_ISDIR(statbuf.st_mode)== 0)   // not a directory
	{
		remove(pathname);
		return 0;
	}
	else
	{
		dp = opendir(pathname);
		if(dp == NULL)
		{
			return -2;
		}
		
		while((dirp = readdir(dp)) != NULL)
		{
			if(strcmp(dirp->d_name,".")==0 || strcmp(dirp->d_name,"..")==0)
			{
				continue;
			}
			char fullpath[256];
			strncpy(fullpath,pathname,255);
			strncat(fullpath,"/",255);
			strncat(fullpath,dirp->d_name,255);
			DelFile(fullpath);
		}
		closedir(dp);
		rmdir(pathname);
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值