用递归删除目录(多个目录可以从参数传进来)
#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]);
}
}