在 CentOS 系统中,使用 readdir
函数可以遍历目录中的文件。以下是一个简单的示例,展示如何使用 C 语言编写一个程序来批量处理目录中的文件:
sudo yum install gcc
readdir_example.c
的文件,并将以下代码粘贴到文件中:#include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <string.h> #include <sys/stat.h> int main(int argc, char *argv[]) { if (argc != 2) { printf("Usage: %s <directory_path>\n", argv[0]); return 1; } char *dir_path = argv[1]; struct dirent *entry; DIR *dp = opendir(dir_path); if (!dp) { perror("opendir"); return 1; } while ((entry = readdir(dp)) != NULL) { if (entry->d_type == DT_REG) { // 只处理普通文件 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) == 0) { printf("Processing file: %s\n", file_path); // 在这里添加你需要对文件执行的操作 } } } closedir(dp); return 0; }
gcc
编译:gcc readdir_example.c -o readdir_example
./readdir_example /path/to/your/directory
这个程序会遍历指定目录中的所有普通文件,并打印出文件路径。你可以根据需要在 printf
语句之后添加对文件执行的操作。