C语言目录操作(2024.8.12)

用递归删除目录(多个目录可以从参数传进来)

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


/*
从目录中读到的所谓目录项,是一个这样的结构体:
struct dirent
{
	ino_t d_ino; // 文件索引号
	off_t d_off; //  目录项偏移量
	unsigned short d_reclen; // 该目录项大小
	unsigned char d_type; // 文件类型如下
	char d_name[256]; // 文件名
};*/
/*********************目录项中文件类型d_type的所有类型的宏定义***********************************************/
/*
		DT_BLK      This is a block device.

       DT_CHR      This is a character device.

       DT_DIR      This is a directory.

       DT_FIFO     This is a named pipe (FIFO).

       DT_LNK      This is a symbolic link.

       DT_REG      This is a regular file.

       DT_SOCK     This is a UNIX domain socket.

       DT_UNKNOWN  The file type is unknown.*/




void del_dir(char* argv)
{
	DIR* dp = opendir(argv);
	while(1)
	{
		struct dirent*dt = readdir(dp);
		if(NULL == dt)
		{
			break;
		}
		if(strcmp(dt->d_name,".") == 0 || strcmp(dt->d_name,"..") == 0)
		{
			continue;		
		}
		if(dt->d_type == DT_REG)
		{
			char* pathname = malloc(1024);
			
			snprintf(pathname,1024,"%s/%s",argv,dt->d_name);
			
			printf("%s\n",pathname);
			
			unlink(pathname);
			
		}
		if(dt->d_type == DT_DIR)
		{
			char* pathname = malloc(1024);
			
			snprintf(pathname,1024,"%s/%s",argv,dt->d_name);
			
			printf("%s\n",pathname);
			
			del_dir(pathname);
			
			rmdir(pathname);
			
		}
		rmdir(argv);
	}
	
	
}

int main(int argc,char** argv)
{
	int i=1;
	for(i;i<argc;i++)
	{
		del_dir(argv[i]);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

向風而行

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值