20240812文件IO

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

#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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值