用C语言实现文件批量改名,检索,目录
时间: 2023-12-09 18:03:59 浏览: 87
程序实现文件的批量改名
好的,以下是一个简单的 C 语言代码示例,可以实现文件批量改名,检索和目录操作:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
void rename_files(const char *dir_path, const char *old_name, const char *new_name) {
DIR *dir;
struct dirent *entry;
dir = opendir(dir_path);
if (dir == NULL) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_REG && strstr(entry->d_name, old_name) != NULL) {
char old_path[PATH_MAX];
char new_path[PATH_MAX];
snprintf(old_path, PATH_MAX, "%s/%s", dir_path, entry->d_name);
snprintf(new_path, PATH_MAX, "%s/%s", dir_path, new_name);
if (rename(old_path, new_path) != 0) {
perror("rename");
}
}
}
closedir(dir);
}
void search_files(const char *dir_path, const char *search_str) {
DIR *dir;
struct dirent *entry;
dir = opendir(dir_path);
if (dir == NULL) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_REG && strstr(entry->d_name, search_str) != NULL) {
printf("%s/%s\n", dir_path, entry->d_name);
} else if (entry->d_type == DT_DIR && strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
char sub_path[PATH_MAX];
snprintf(sub_path, PATH_MAX, "%s/%s", dir_path, entry->d_name);
search_files(sub_path, search_str);
}
}
closedir(dir);
}
int main() {
const char *dir_path = "/path/to/directory";
const char *old_name = "old_name";
const char *new_name = "new_name";
const char *search_str = "search_string";
// 批量重命名
rename_files(dir_path, old_name, new_name);
// 检索文件
search_files(dir_path, search_str);
return 0;
}
```
请注意,此示例仅供参考,您需要根据自己的具体需求进行修改和扩展。同时,为了确保程序的正确性和安全性,请务必仔细检查您的代码并进行充分测试。
阅读全文