Linux系统——rm命令的代码实现

本文介绍了一种在Linux系统中使用C语言实现rm-rf命令的方法,详细解释了如何递归删除非空目录及其包含的所有文件和子目录。通过使用opendir, readdir, chdir, remove等函数,实现了对指定目录及其内容的彻底删除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现Linux系统下rm -rf xxx删除非空目录的功能

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

void del_stat(const char* name)
{
	DIR* fl = opendir(name);
	chdir(name);
	
	for(struct dirent* dir = readdir(fl); NULL!=dir;)
	{
		if(dir->d_type == DT_DIR)
		{
			if(strcmp(dir->d_name,"..")&&strcmp(dir->d_name,"."))
				del_stat(dir->d_name);
		}
		remove(dir->d_name);
		dir = readdir(fl);
	}
	chdir("..");
	remove(name);
}

int main(int argc,char *argv[])
{
	if(3 != argc)
	{
		printf("User:./rm -rf xxx\n");
		return -1;
	}
	
	struct stat sta;
	if(0 > stat(argv[2],&sta))
	{
		perror("open");
		return -1;
	}

	if(!S_ISDIR(sta.st_mode))
	{
		char temp;
		printf("该文件是一个文件,是否删除(y)、(n):");
		scanf("%c",&temp);
		if(temp == 'n')return 0;
		remove(argv[2]);
		return 0;
	}
	
	del_stat(argv[2]);
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值