linux

如何用copendir删除目录

小樊
60
2025-07-26 10:44:14
栏目: 编程语言

copendir 函数本身并不用于删除目录,而是用于打开一个目录流,以便读取目录中的条目。要删除目录,您可以使用 rmdirrm -r(在 Unix/Linux 系统上)命令。

以下是使用 C 语言和 opendirreaddirclosedir 函数删除目录的示例:

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

int remove_directory(const char *path) {
    struct dirent *entry;
    DIR *dp = opendir(path);

    if (dp == NULL) {
        perror("opendir");
        return -1;
    }

    while ((entry = readdir(dp)) != NULL) {
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        char full_path[PATH_MAX];
        snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);

        if (remove(full_path) != 0) {
            perror("remove");
            closedir(dp);
            return -1;
        }
    }

    closedir(dp);

    if (rmdir(path) != 0) {
        perror("rmdir");
        return -1;
    }

    return 0;
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
        return 1;
    }

    if (remove_directory(argv[1]) == 0) {
        printf("Directory removed successfully.\n");
    } else {
        printf("Failed to remove directory.\n");
    }

    return 0;
}

这个程序接受一个目录路径作为参数,并尝试删除该目录及其所有内容。请注意,这个程序不会删除非空目录,除非您使用 rm -r 命令。

0
看了该问题的人还看了