linux

linux copendir怎样列出目录内容

小樊
83
2024-12-28 22:02:11
栏目: 智能运维

copendir 是一个在 C 语言中使用的函数,用于创建一个指向另一个目录的副本

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

int copendir(const char *src, const char *dest) {
    DIR *src_dir, *dest_dir;
    struct dirent *entry;
    struct stat statbuf;

    // 打开源目录
    if ((src_dir = opendir(src)) == NULL) {
        perror("opendir");
        return -1;
    }

    // 创建目标目录
    if (mkdir(dest, 0777) < 0) {
        perror("mkdir");
        closedir(src_dir);
        return -1;
    }

    // 复制源目录中的每个条目到目标目录
    while ((entry = readdir(src_dir)) != NULL) {
        // 获取源条目的完整路径
        char src_path[PATH_MAX];
        snprintf(src_path, sizeof(src_path), "%s/%s", src, entry->d_name);

        // 获取源条目的状态信息
        if (stat(src_path, &statbuf) < 0) {
            perror("stat");
            continue;
        }

        // 如果是一个目录,则递归复制
        if (S_ISDIR(statbuf.st_mode)) {
            if (copendir(src_path, dest_path) < 0) {
                perror("copendir");
                continue;
            }
        } else {
            // 复制文件到目标目录
            char dest_path[PATH_MAX];
            snprintf(dest_path, sizeof(dest_path), "%s/%s", dest, entry->d_name);

            if (link(src_path, dest_path) < 0) {
                perror("link");
            }
        }
    }

    // 关闭源目录
    closedir(src_dir);

    return 0;
}

int main() {
    const char *src = "/path/to/source";
    const char *dest = "/path/to/destination";

    if (copendir(src, dest) < 0) {
        fprintf(stderr, "Failed to copy directory %s to %s\n", src, dest);
        return EXIT_FAILURE;
    }

    printf("Directory %s copied to %s successfully\n", src, dest);
    return EXIT_SUCCESS;
}

这个程序定义了一个名为 copendir 的函数,它接受两个参数:源目录路径和目标目录路径。它会递归地复制源目录中的所有文件和子目录到目标目录。在 main 函数中,我们调用 copendir 函数并传入源目录和目标目录的路径。如果复制成功,程序将输出成功消息;否则,将输出错误消息。

0
看了该问题的人还看了