ubuntu

ubuntu readdir如何实现文件迁移

小樊
36
2025-10-13 16:00:10
栏目: 智能运维

在Ubuntu系统中,使用readdir函数可以帮助你遍历目录中的文件和子目录。如果你想要实现文件的迁移,可以结合readdir和其他文件操作函数来完成。以下是一个简单的示例,展示如何使用C语言和readdir函数来迁移一个目录中的所有文件到另一个目录:

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

void migrate_files(const char *source_dir, const char *dest_dir) {
    DIR *dir;
    struct dirent *entry;
    char source_path[1024], dest_path[1024];

    // 打开源目录
    dir = opendir(source_dir);
    if (dir == NULL) {
        perror("opendir");
        return;
    }

    // 遍历源目录中的所有条目
    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_dir, entry->d_name);
        snprintf(dest_path, sizeof(dest_path), "%s/%s", dest_dir, entry->d_name);

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

        // 如果是普通文件,则进行迁移
        if (S_ISREG(st.st_mode)) {
            FILE *src_file = fopen(source_path, "rb");
            FILE *dest_file = fopen(dest_path, "wb");

            if (src_file == NULL || dest_file == NULL) {
                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);

            // 删除源文件
            if (remove(source_path) != 0) {
                perror("remove");
            }
        }
    }

    // 关闭目录
    closedir(dir);
}

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

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

    migrate_files(source_dir, dest_dir);

    return EXIT_SUCCESS;
}

编译和运行

  1. 将上述代码保存为一个文件,例如migrate_files.c
  2. 打开终端并导航到保存文件的目录。
  3. 使用以下命令编译代码:
    gcc -o migrate_files migrate_files.c
    
  4. 运行程序并提供源目录和目标目录作为参数:
    ./migrate_files /path/to/source /path/to/destination
    

注意事项

这个示例展示了如何使用readdir函数遍历目录并迁移文件。你可以根据需要扩展和修改这个程序以满足更复杂的需求。

0
看了该问题的人还看了