温馨提示×

readdir如何实现目录同步

小樊
45
2025-12-31 00:31:13
栏目: 编程语言

readdir 是一个用于读取目录内容的函数,通常在 C 语言中使用。要实现目录同步,你需要比较两个目录的内容,并根据需要添加、删除或更新文件。以下是一个简单的示例,展示了如何使用 readdir 实现目录同步:

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

void sync_directories(const char *dir1, const char *dir2) {
    DIR *dp1 = opendir(dir1);
    DIR *dp2 = opendir(dir2);

    if (!dp1 || !dp2) {
        perror("opendir");
        exit(EXIT_FAILURE);
    }

    struct dirent *entry;
    while ((entry = readdir(dp1)) != NULL) {
        char path1[1024], path2[1024];
        snprintf(path1, sizeof(path1), "%s/%s", dir1, entry->d_name);
        snprintf(path2, sizeof(path2), "%s/%s", dir2, entry->d_name);

        struct stat st1, st2;
        if (stat(path1, &st1) == -1 || stat(path2, &st2) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(st1.st_mode) && S_ISDIR(st2.st_mode)) {
            sync_directories(path1, path2);
        } else if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        } else {
            if (access(path2, F_OK) == -1) {
                printf("Adding file: %s\n", path2);
                // 在这里添加文件同步的代码,例如使用 system() 调用 cp 命令
            } else if (memcmp(&st1, &st2, sizeof(st1)) != 0) {
                printf("Updating file: %s\n", path2);
                // 在这里添加文件同步的代码,例如使用 system() 调用 cp 命令
            }
        }
    }

    closedir(dp1);
    closedir(dp2);

    // 删除 dir2 中存在但 dir1 中不存在的文件
    dp1 = opendir(dir1);
    dp2 = opendir(dir2);

    while ((entry = readdir(dp2)) != NULL) {
        char path1[1024], path2[1024];
        snprintf(path1, sizeof(path1), "%s/%s", dir1, entry->d_name);
        snprintf(path2, sizeof(path2), "%s/%s", dir2, entry->d_name);

        struct stat st1, st2;
        if (stat(path1, &st1) == -1 || stat(path2, &st2) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(st1.st_mode) && S_ISDIR(st2.st_mode)) {
            sync_directories(path1, path2);
        } else if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        } else {
            if (access(path1, F_OK) == -1) {
                printf("Deleting file: %s\n", path2);
                // 在这里添加文件同步的代码,例如使用 system() 调用 rm 命令
            }
        }
    }

    closedir(dp1);
    closedir(dp2);
}

int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("Usage: %s <dir1> <dir2>\n", argv[0]);
        return EXIT_FAILURE;
    }

    sync_directories(argv[1], argv[2]);

    return EXIT_SUCCESS;
}

这个示例程序会比较两个目录(dir1dir2)的内容,并根据需要添加、删除或更新文件。请注意,这个示例仅用于演示目的,实际应用中可能需要更复杂的错误处理和功能。

0