温馨提示×

readdir在Linux中如何实现文件备份与恢复

小樊
40
2025-10-30 01:56:56
栏目: 智能运维

在Linux中,readdir函数通常用于遍历目录中的文件和子目录。要使用readdir实现文件备份与恢复,你需要结合其他系统调用和库函数来完成整个过程。以下是一个简单的示例,展示了如何使用readdir进行文件备份:

文件备份

#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 == -1) {
        perror("open source file");
        return;
    }

    int dst_fd = open(dst, O_WRONLY | O_CREAT, 0644);
    if (dst_fd == -1) {
        perror("open destination file");
        close(src_fd);
        return;
    }

    char buffer[4096];
    ssize_t bytes_read, bytes_written;

    while ((bytes_read = read(src_fd, buffer, sizeof(buffer))) > 0) {
        bytes_written = write(dst_fd, buffer, bytes_read);
        if (bytes_written != bytes_read) {
            perror("write to destination file");
            break;
        }
    }

    if (bytes_read == -1) {
        perror("read from source 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;
    }

    // Create destination directory if it doesn't exist
    mkdir(dst_dir, 0755);

    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) {
        fprintf(stderr, "Usage: %s <source_directory> <destination_directory>
", argv[0]);
        return 1;
    }

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

文件恢复

文件恢复的过程与备份类似,但方向相反。你需要遍历备份目录中的文件和子目录,并将它们复制回原始位置。

void restore_directory(const char *src_dir, const char *dst_dir) {
    // ... (similar to backup_directory, but copy files from src_dir to dst_dir)
}

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

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

注意事项

  1. 错误处理:在实际应用中,你需要更详细的错误处理和日志记录。
  2. 权限:确保你有足够的权限读取源目录和写入目标目录。
  3. 符号链接:处理符号链接时需要特别小心,以避免无限循环或覆盖重要文件。
  4. 大文件:对于非常大的文件,可能需要更大的缓冲区或分块处理。

通过这种方式,你可以使用readdir函数结合其他系统调用来实现文件的备份与恢复。

0