用递归删除目录(多个目录可以从参数传进来)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
// 递归删除目录及其子目录
void rmdir_recursive(char* path);
int main(int argc, char* argv[])
{
if (argc != 2)
{
fprintf(stderr, "Usage: %s directory\n", argv[0]);
exit(1);
}
rmdir_recursive(argv[1]);
return 0;
}
void rmdir_recursive(char* path)
{
DIR *dir; // 目录句柄
struct dirent *ptr; // 目录项指针
struct stat st; // 文件状态
if (lstat(path, &st) == -1) // 判断是否存在
{
perror("lstat");
exit(1);
}
if (!S_ISDIR(st.st_mode))
{
fprintf(stderr, "%s is not a directory\n", path); // 不是目录
exit(1);
}
dir = opendir(path);
if (dir == NULL)
{
perror("opendir");
exit(1);
}
while ((ptr = readdir(dir)) != NULL)
{
if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0)
continue;
char subpath[1024];
snprintf(subpath, sizeof(subpath), "%s/%s", path, ptr->d_name);
if (lstat(subpath, &st) == -1)
{
perror("lstat");
exit(1);
}
if (S_ISDIR(st.st_mode)) // 是目录
{
rmdir_recursive(subpath);
}
else if (unlink(subpath) == -1) // 是文件,删除
{
perror("unlink");
exit(1);
}
}
if (closedir(dir) == -1)
{
perror("closedir");
exit(1);
}
if (rmdir(path) == -1) // 删除目录自身
{
perror("rmdir");
exit(1);
}
}