在Linux中,readdir函数通常用于遍历目录中的文件和子目录。要实现批量重命名,你可以结合使用readdir和其他文件操作函数(如rename)。以下是一个简单的示例,展示了如何使用C语言和readdir函数来批量重命名目录中的文件:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s <directory> <new_prefix>
", argv[0]);
return 1;
}
char *dir_path = argv[1];
char new_prefix[256] = argv[2];
DIR *dir;
struct dirent *entry;
struct stat file_stat;
int count = 0;
dir = opendir(dir_path);
if (!dir) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
// Skip current and parent directories
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// Construct full file path
char old_path[512];
snprintf(old_path, sizeof(old_path), "%s/%s", dir_path, entry->d_name);
// Get file status
if (stat(old_path, &file_stat) == -1) {
perror("stat");
continue;
}
// Check if it's a regular file
if (!S_ISREG(file_stat.st_mode)) {
continue;
}
// Construct new file name with prefix and count
char new_name[256];
snprintf(new_name, sizeof(new_name), "%s_%d%s", new_prefix, count++, entry->d_name);
// Construct new file path
char new_path[512];
snprintf(new_path, sizeof(new_path), "%s/%s", dir_path, new_name);
// Rename the file
if (rename(old_path, new_path) == -1) {
perror("rename");
}
}
closedir(dir);
printf("Renamed %d files in directory %s
", count, dir_path);
return 0;
}
rename_files.c。gcc -o rename_files rename_files.c
./rename_files /path/to/directory new_prefix
opendir 打开目录。readdir 读取目录中的条目。stat 获取文件的状态信息。rename 重命名文件。closedir 关闭目录。这个程序会遍历指定目录中的所有文件,并将它们重命名为新前缀加上一个递增的数字。例如,如果目录中有文件file1.txt和file2.txt,并且新前缀是new_,那么它们将被重命名为new_1.txt和new_2.txt。
请注意,这个程序假设目录中的文件名不会导致重命名后的文件名冲突。如果存在冲突,rename函数会失败,并且程序会输出错误信息。