linux

Linux readdir如何实现目录备份功能

小樊
37
2025-06-14 04:19:28
栏目: 智能运维

在Linux中,readdir函数通常与opendirclosedir以及dirent结构体一起使用,用于读取目录的内容。要实现目录备份功能,你需要遍历目标目录及其所有子目录,并将文件和子目录复制到备份位置。以下是一个简单的示例,展示了如何使用这些函数来实现目录备份:

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

void backup_directory(const char *source, const char *destination) {
    DIR *dir;
    struct dirent *entry;
    struct stat statbuf;
    char source_path[1024], dest_path[1024];

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

    // 创建目标目录(如果不存在)
    mkdir(destination, 0755);

    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, entry->d_name);
        // 构建目标文件/目录的完整路径
        snprintf(dest_path, sizeof(dest_path), "%s/%s", destination, entry->d_name);

        // 获取文件/目录的属性
        if (stat(source_path, &statbuf) == -1) {
            perror("stat");
            continue;
        }

        // 如果是目录,则递归备份
        if (S_ISDIR(statbuf.st_mode)) {
            backup_directory(source_path, dest_path);
        } else {
            // 如果是文件,则进行复制
            FILE *src_file = fopen(source_path, "rb");
            FILE *dest_file = fopen(dest_path, "wb");

            if (!src_file || !dest_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, dest_file);
            }

            fclose(src_file);
            fclose(dest_file);
        }
    }

    closedir(dir);
}

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;
}

说明:

  1. opendir: 打开目录。
  2. readdir: 读取目录中的条目。
  3. closedir: 关闭目录。
  4. stat: 获取文件或目录的属性。
  5. mkdir: 创建目录(如果不存在)。
  6. fopen, fread, fwrite, fclose: 文件操作函数,用于复制文件内容。

使用方法:

编译并运行程序,传入源目录和目标目录作为参数:

gcc -o backup_backup_directory.c
./backup_directory /path/to/source /path/to/destination

这个示例程序会递归地遍历源目录及其所有子目录,并将文件复制到目标目录中。请注意,这个示例没有处理符号链接、设备文件、权限问题等复杂情况,实际使用时可能需要根据具体需求进行扩展和改进。

0
看了该问题的人还看了