温馨提示×

ubuntu readdir如何实现批量操作文件

小樊
49
2025-10-18 01:48:27
栏目: 智能运维

在Ubuntu中,使用readdir函数可以遍历目录中的文件和子目录。要实现批量操作文件,你可以结合readdir和其他文件操作函数(如opendirclosedirstat等)来完成。以下是一个简单的示例,展示了如何使用readdir遍历目录并对文件执行批量操作:

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

void process_file(const char *path) {
    // 在这里实现对单个文件的操作
    printf("处理文件: %s\n", path);
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("用法: %s <目录路径>\n", argv[0]);
        return 1;
    }

    const char *dir_path = argv[1];
    DIR *dir = opendir(dir_path);
    if (dir == NULL) {
        perror("无法打开目录");
        return 1;
    }

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        // 忽略当前目录(".")和上级目录("..")
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // 拼接文件的完整路径
        char file_path[1024];
        snprintf(file_path, sizeof(file_path), "%s/%s", dir_path, entry->d_name);

        // 对文件执行操作
        process_file(file_path);
    }

    closedir(dir);
    return 0;
}

将上述代码保存为batch_process.c,然后使用以下命令编译:

gcc -o batch_process batch_process.c

现在你可以使用这个程序对指定目录中的所有文件执行批量操作。例如,要处理/home/user/documents目录中的所有文件,可以运行:

./batch_process /home/user/documents

请注意,这个示例仅用于演示目的。在实际应用中,你可能需要根据需求修改process_file函数以实现所需的文件操作。

0