在Ubuntu中,readdir函数用于读取目录中的文件和子目录。要实现批量操作,你可以结合readdir函数和其他文件操作函数(如opendir、closedir、stat等)来遍历目录并对文件执行所需的操作。
以下是一个简单的示例,展示了如何使用readdir函数批量读取目录中的所有文件,并对每个文件执行某个操作(例如,打印文件名):
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
int main() {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
char path[1024];
// 打开目录
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
// 遍历目录中的文件和子目录
while ((entry = readdir(dir)) != NULL) {
// 跳过当前目录(.)和上级目录(..)
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 构建文件的完整路径
snprintf(path, sizeof(path), "./%s", entry->d_name);
// 获取文件的状态信息
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
// 检查是否为普通文件
if (S_ISREG(file_stat.st_mode)) {
// 在这里执行你的批量操作,例如打印文件名
printf("File: %s\n", entry->d_name);
}
}
// 关闭目录
closedir(dir);
return EXIT_SUCCESS;
}
这个示例程序会读取当前目录中的所有文件(不包括子目录),并打印它们的文件名。你可以根据需要修改这个程序,以实现你想要的批量操作。