linux

Linux readdir如何实现文件备份

小樊
45
2025-04-26 15:04:58
栏目: 智能运维

在Linux中,使用readdir函数可以遍历目录中的文件和子目录。要实现文件备份,你可以结合readdir函数和其他文件操作函数(如fopenfreadfwrite等)来读取源目录中的文件,并将它们复制到目标目录。以下是一个简单的示例:

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

void backup_file(const char *src, const char *dst) {
    int src_fd = open(src, O_RDONLY);
    if (src_fd < 0) {
        perror("open source file");
        return;
    }

    int dst_fd = open(dst, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
    if (dst_fd < 0) {
        perror("open destination file");
        close(src_fd);
        return;
    }

    char buffer[4096];
    ssize_t n;
    while ((n = read(src_fd, buffer, sizeof(buffer))) > 0) {
        write(dst_fd, buffer, n);
    }

    if (n < 0) {
        perror("read/write file");
    }

    close(src_fd);
    close(dst_fd);
}

void backup_directory(const char *src_dir, const char *dst_dir) {
    struct dirent *entry;
    DIR *dp = opendir(src_dir);

    if (!dp) {
        perror("opendir");
        return;
    }

    // 创建目标目录
    mkdir(dst_dir, S_IRWXU | S_IRWXG | S_IRWXO);

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

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

        struct stat st;
        if (stat(src_path, &st) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(st.st_mode)) {
            backup_directory(src_path, dst_path);
        } else {
            backup_file(src_path, dst_path);
        }
    }

    closedir(dp);
}

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

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

这个示例程序接受两个命令行参数:源目录和目标目录。它会遍历源目录中的所有文件和子目录,并将它们复制到目标目录。注意,这个程序不会处理符号链接、设备文件等特殊类型的文件。你可以根据需要扩展此程序以满足你的需求。

0
看了该问题的人还看了