溫馨提示×

如何用copendir刪除目錄

小樊
48
2025-07-26 10:44:14
欄目: 編程語言

copendir 函數本身并不用于刪除目錄,而是用于打開一個目錄流,以便讀取目錄中的條目。要刪除目錄,您可以使用 rmdirrm -r(在 Unix/Linux 系統上)命令。

以下是使用 C 語言和 opendir、readdirclosedir 函數刪除目錄的示例:

#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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女