温馨提示×

CentOS readdir如何实现目录迁移

小樊
48
2025-07-10 19:15:02
栏目: 智能运维

在 CentOS 系统中,使用 readdir 函数可以帮助你读取目录中的文件和子目录。如果你想要实现目录的迁移,你可以结合 readdir 函数和其他文件操作函数来完成这个任务。以下是一个简单的示例,展示了如何使用 readdir 函数迁移一个目录:

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

void migrate_directory(const char *src, const char *dst) {
    DIR *dir;
    struct dirent *entry;
    struct stat statbuf;
    char src_path[1024], dst_path[1024];

    if (!(dir = opendir(src))) {
        perror("opendir");
        return;
    }

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

        snprintf(src_path, sizeof(src_path), "%s/%s", src, entry->d_name);
        snprintf(dst_path, sizeof(dst_path), "%s/%s", dst, entry->d_name);

        if (lstat(src_path, &statbuf) == -1) {
            perror("lstat");
            continue;
        }

        if (S_ISDIR(statbuf.st_mode)) {
            mkdir(dst_path, statbuf.st_mode);
            migrate_directory(src_path, dst_path);
        } else {
            FILE *src_file = fopen(src_path, "rb");
            FILE *dst_file = fopen(dst_path, "wb");

            if (!src_file || !dst_file) {
                perror("fopen");
                continue;
            }

            char buffer[1024];
            size_t n;

            while ((n = fread(buffer, 1, sizeof(buffer), src_file)) > 0) {
                fwrite(buffer, 1, n, dst_file);
            }

            fclose(src_file);
            fclose(dst_file);
        }
    }

    closedir(dir);
}

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

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

    return 0;
}

这个示例程序接受两个命令行参数:源目录和目标目录。它会递归地将源目录中的所有文件和子目录复制到目标目录中。注意,这个程序不会删除源目录中的文件,如果你需要在迁移完成后删除源目录,可以使用 rmdirremove 函数。

编译并运行这个程序:

gcc -o migrate_directory migrate_directory.c
./migrate_directory /path/to/source /path/to/destination

请确保你有足够的权限来读取源目录和写入目标目录。

0