以下是一个C语言程序的示例,该程序使用`tar`命令解压指定的tar文件到一个目录,然后遍历这个目录以查找文件名中包含指定字符串的文件,并将这些文件重命名。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <ctype.h>
// 函数:将字符串转换为小写
void to_lower_case(char *str) {
for (int i = 0; str[i]; i++) {
str[i] = tolower(str[i]);
}
}
// 函数:解压tar文件到指定目录
int extract_tar_file(const char *tar_file, const char *output_dir) {
char command[256];
sprintf(command, "tar -xf %s -C %s", tar_file, output_dir);
return system(command);
}
// 函数:遍历目录并重命名包含指定字符串的文件
void rename_files(const char *dir_path, const char *search_str, const char *new_name) {
DIR *dir;
struct dirent *entry;
char path[1024];
char lower_name[256];
char new_file_name[1024];
dir = opendir(dir_path);
if (dir == NULL) {
perror("Failed to open directory");
return;
}
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_DIR) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
sprintf(path, "%s/%s", dir_path, entry->d_name);
rename_files(path, search_str, new_name);
} else {
strcpy(lower_name, entry->d_name);
to_lower_case(lower_name);
if (strstr(lower_name, search_str) != NULL) {
sprintf(path, "%s/%s", dir_path, entry->d_name);
sprintf(new_file_name, "%s/%s", dir_path, new_name);
if (rename(path, new_file_name) == 0) {
printf("Renamed %s to %s\n", path, new_file_name);
} else {
perror("Failed to rename file");
}
}
}
}
closedir(dir);
}
int main() {
const char *tar_file = "example.tar";
const char *output_dir = "./extracted";
const char *search_str = "target";
const char *new_name = "new_filename.txt";
// 将搜索字符串转换为小写,以实现大小写不敏感的搜索
char search_str_lower[256];
strcpy(search_str_lower, search_str);
to_lower_case(search_str_lower);
if (extract_tar_file(tar_file, output_dir) != 0) {
fprintf(stderr, "Failed to extract tar file\n");
return 1;
}
rename_files(output_dir, search_str_lower, new_name);
return 0;
}
说明:
1. 解压tar文件:使用system函数调用tar命令。
2. 遍历目录:使用opendir和readdir函数遍历目录。
3. 重命名文件:当找到包含指定字符串的文件时,使用rename函数进行重命名。
4. 大小写不敏感搜索:通过将文件名转换为小写并搜索小写字符串实现。
确保在运行此程序之前,你的系统中已安装了tar命令,并且有权限创建和修改文件。