温馨提示×

ubuntu readdir如何实现目录备份

小樊
43
2025-10-03 07:01:05
栏目: 智能运维

在Ubuntu系统中,你可以使用readdir函数来实现目录备份。readdir函数是C语言中的一个库函数,用于读取目录中的文件和子目录。以下是一个简单的示例,展示了如何使用readdir函数来备份一个目录:

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

void backup_directory(const char *source_dir, const char *backup_dir) {
    DIR *dir;
    struct dirent *entry;
    struct stat file_stat;
    char source_path[1024], backup_path[1024];

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

    if (mkdir(backup_dir, 0755) == -1 && errno != EEXIST) {
        perror("mkdir");
        closedir(dir);
        return;
    }

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

        snprintf(source_path, sizeof(source_path), "%s/%s", source_dir, entry->d_name);
        snprintf(backup_path, sizeof(backup_path), "%s/%s", backup_dir, entry->d_name);

        if (stat(source_path, &file_stat) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(file_stat.st_mode)) {
            backup_directory(source_path, backup_path);
        } else {
            FILE *src_file = fopen(source_path, "rb");
            FILE *dst_file = fopen(backup_path, "wb");

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

            char buffer[1024];
            size_t bytes_read;

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

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

    closedir(dir);
}

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

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

    return 0;
}

这个程序接受两个命令行参数:源目录和备份目录。它会递归地遍历源目录中的所有文件和子目录,并将它们复制到备份目录中。请注意,这个程序仅适用于文件,不适用于符号链接、设备文件等特殊文件类型。

要编译并运行此程序,请将其保存为backup.c,然后在终端中执行以下命令:

gcc -o backup backup.c
./backup /path/to/source/directory /path/to/backup/directory

这将编译程序并使用指定的源目录和备份目录运行它。

0