debian

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

小樊
45
2025-07-15 16:43:46
栏目: 智能运维

在Debian系统中,使用readdir函数可以帮助你遍历目录并获取目录中的文件列表。为了实现文件备份,你可以编写一个简单的C程序来读取源目录中的所有文件,并将它们复制到目标目录中。以下是一个基本的示例代码,展示了如何使用readdirshutil库来实现文件备份:

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

void backup_file(const char *src, const char *dest) {
    FILE *src_file = fopen(src, "rb");
    FILE *dest_file = fopen(dest, "wb");

    if (src_file == NULL || dest_file == NULL) {
        perror("Error opening file");
        return;
    }

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

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

    const char *src_dir = argv[1];
    const char *dest_dir = argv[2];

    struct dirent *entry;
    DIR *dp = opendir(src_dir);

    if (dp == NULL) {
        perror("opendir");
        return 1;
    }

    while ((entry = readdir(dp)) != NULL) {
        if (entry->d_type == DT_REG) { // Only regular files
            char src_path[1024], dest_path[1024];
            snprintf(src_path, sizeof(src_path), "%s/%s", src_dir, entry->d_name);
            snprintf(dest_path, sizeof(dest_path), "%s/%s", dest_dir, entry->d_name);

            // Ensure the destination directory exists
            struct stat st = {0};
            if (stat(dest_dir, &st) == -1) {
                mkdir(dest_dir, 0755);
            }

            backup_file(src_path, dest_path);
        }
    }

    closedir(dp);
    return 0;
}

编译和运行

  1. 将上述代码保存为backup.c
  2. 打开终端并导航到保存backup.c的目录。
  3. 使用以下命令编译代码:
    gcc -o backup backup.c
    
  4. 运行备份程序,指定源目录和目标目录:
    ./backup /path/to/source /path/to/destination
    

注意事项

通过这种方式,你可以使用Debian系统中的readdir函数来实现文件备份。

0
看了该问题的人还看了