使用tar命令解压指定文件成目录,并遍历这个目录,查找文件名中包含指定字符串(大小写不敏感)的文件,将其重命名成另一个文件

以下是一个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命令,并且有权限创建和修改文件。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值