在Debian系统中,readdir
函数通常用于读取目录的内容。如果你想要对目录中的文件进行批量操作,你可以结合使用opendir
、readdir
和closedir
函数,以及一些其他的文件操作函数。下面是一个简单的示例,展示了如何使用这些函数来遍历一个目录并对其中的每个文件执行某个操作(例如,打印文件名):
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void process_file(const char *path) {
// 这里可以添加你想要对每个文件执行的操作
printf("Processing file: %s\n", path);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return EXIT_FAILURE;
}
const char *dir_path = argv[1];
DIR *dir = opendir(dir_path);
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 忽略当前目录和上级目录的特殊条目
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 构建文件的完整路径
char file_path[PATH_MAX];
snprintf(file_path, sizeof(file_path), "%s/%s", dir_path, entry->d_name);
// 获取文件信息
struct stat file_stat;
if (stat(file_path, &file_stat) == -1) {
perror("stat");
continue;
}
// 检查是否为常规文件
if (S_ISREG(file_stat.st_mode)) {
process_file(file_path);
}
}
closedir(dir);
return EXIT_SUCCESS;
}
这个程序接受一个目录路径作为命令行参数,然后遍历该目录中的所有文件和子目录。对于每个常规文件,它调用process_file
函数来处理文件。在这个示例中,process_file
函数只是简单地打印出文件的路径,但你可以根据需要修改它来执行任何你需要的操作。
要编译这个程序,你可以使用gcc
:
gcc -o list_files list_files.c
然后运行它,传入你想要操作的目录路径:
./list_files /path/to/directory
请注意,这个程序没有递归地处理子目录。如果你需要递归地处理目录树中的所有文件,你需要编写额外的代码来递归地调用这个函数。