温馨提示×

如何通过readdir实现Debian文件备份

小樊
47
2025-11-10 21:27:02
栏目: 智能运维

要通过readdir实现Debian文件备份,你需要编写一个程序来遍历源目录中的所有文件和子目录,并将它们复制到目标目录。以下是一个使用C语言和dirent.h库实现的简单示例:

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

void backup_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 (stat(src_path, &statbuf) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(statbuf.st_mode)) {
            mkdir(dst_path, statbuf.st_mode);
            backup_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 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> <destination_directory>\n", argv[0]);
        return 1;
    }

    const char *src = argv[1];
    const char *dst = argv[2];

    backup_directory(src, dst);

    return 0;
}

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

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

gcc -o backup backup.c

现在你可以使用以下命令运行备份程序:

./backup /path/to/source/directory /path/to/destination/directory

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

0