温馨提示×

Linux copendir如何实现目录的同步与合并

小樊
34
2026-01-01 19:23:05
栏目: 智能运维

在Linux中,copendir函数本身并不直接提供目录同步与合并的功能。copendir函数主要用于复制一个目录流的句柄,通常用于遍历目录结构。要实现目录的同步与合并,你需要编写额外的代码来处理文件的比较、复制、删除等操作。

以下是一个简单的示例,展示了如何使用opendirreaddir等函数来实现目录的同步与合并:

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

void sync_and_merge(const char *src_dir, const char *dst_dir) {
    DIR *src_dp = opendir(src_dir);
    if (!src_dp) {
        perror("opendir");
        return;
    }

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

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

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

        struct stat src_stat, dst_stat;
        if (stat(src_path, &src_stat) == -1 || stat(dst_path, &dst_stat) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(src_stat.st_mode)) {
            if (mkdir(dst_path, src_stat.st_mode) == -1 && errno != EEXIST) {
                perror("mkdir");
            } else {
                sync_and_merge(src_path, dst_path);
            }
        } else {
            if (src_stat.st_mtime > dst_stat.st_mtime) {
                if (copy_file(src_path, dst_path) == -1) {
                    perror("copy_file");
                }
            }
        }
    }

    closedir(src_dp);
}

int copy_file(const char *src_path, const char *dst_path) {
    FILE *src_fp = fopen(src_path, "rb");
    if (!src_fp) {
        perror("fopen");
        return -1;
    }

    FILE *dst_fp = fopen(dst_path, "wb");
    if (!dst_fp) {
        perror("fopen");
        fclose(src_fp);
        return -1;
    }

    char buffer[BUFSIZ];
    size_t n;
    while ((n = fread(buffer, 1, sizeof(buffer), src_fp)) > 0) {
        if (fwrite(buffer, 1, n, dst_fp) != n) {
            perror("fwrite");
            fclose(src_fp);
            fclose(dst_fp);
            return -1;
        }
    }

    fclose(src_fp);
    fclose(dst_fp);
    return 0;
}

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

    sync_and_merge(argv[1], argv[2]);
    return 0;
}

这个示例程序接受两个命令行参数:源目录和目标目录。它会遍历源目录中的所有文件和子目录,并将它们同步到目标目录。如果目标目录中不存在某个文件或子目录,程序会创建它;如果目标目录中已存在某个文件,程序会比较它们的修改时间,并在必要时复制较新的文件。

请注意,这个示例程序仅用于演示目的,实际应用中可能需要处理更多的边界情况和错误处理。此外,它不会删除目标目录中存在而源目录中不存在的文件。如果需要实现更复杂的同步和合并功能,可以考虑使用现有的工具,如rsync

0