C++实现批量图片文件重命名的优雅写法求教
更优雅的C++实现方案
你的原有代码逻辑是通顺的,但存在几处可以简化、提升安全性的地方:
- 冗余的char数组拷贝:
rename可以直接接收std::string::c_str()的返回值,不需要额外定义char数组再做strcpy,还能避免固定长度缓冲区溢出的风险 - 硬编码的文件名规则、文件数量可以参数化,后续修改需求时不用翻循环逻辑调整
- 原代码里的旧文件名写的是
- copy.jpg(小写c),你描述的原文件名是- Copy.jpg(大写C),这里大小写不匹配会导致重命名失败,需要注意
轻量优化版(兼容C++11及以上标准)
#include <iostream> #include <cstdio> #include <string> // 把固定规则提为常量,后续修改更方便 constexpr int FILE_COUNT = 50; const std::string OLD_PREFIX = "img ("; const std::string OLD_SUFFIX = ") - Copy.jpg"; const std::string NEW_PREFIX = "picture_"; const std::string NEW_SUFFIX = ".jpg"; int main() { for (int i = 1; i <= FILE_COUNT; ++i) { std::string old_name = OLD_PREFIX + std::to_string(i) + OLD_SUFFIX; std::string new_name = NEW_PREFIX + std::to_string(i) + NEW_SUFFIX; if (std::rename(old_name.c_str(), new_name.c_str()) != 0) { std::perror(("重命名失败: " + old_name).c_str()); } else { std::cout << old_name << " 已成功重命名为 " << new_name << std::endl; } } // 按任意键退出的逻辑可以保留 std::getchar(); return 0; }
C++17 标准更安全的实现(用filesystem库)
如果你用的编译器支持C++17及以上标准,推荐用标准库的filesystem模块做文件操作,类型更安全,错误处理更规范:
#include <iostream> #include <string> #include <filesystem> namespace fs = std::filesystem; constexpr int FILE_COUNT = 50; const std::string OLD_PREFIX = "img ("; const std::string OLD_SUFFIX = ") - Copy.jpg"; const std::string NEW_PREFIX = "picture_"; const std::string NEW_SUFFIX = ".jpg"; int main() { std::error_code ec; for (int i = 1; i <= FILE_COUNT; ++i) { fs::path old_path = OLD_PREFIX + std::to_string(i) + OLD_SUFFIX; fs::path new_path = NEW_PREFIX + std::to_string(i) + NEW_SUFFIX; // 先判断原文件是否存在,避免无意义的错误提示 if (!fs::exists(old_path, ec)) { std::cout << "文件不存在,跳过: " << old_path << std::endl; ec.clear(); continue; } // 避免覆盖已存在的目标文件 if (fs::exists(new_path, ec)) { std::cout << "目标文件已存在,跳过: " << new_path << std::endl; ec.clear(); continue; } fs::rename(old_path, new_path, ec); if (ec) { std::cout << "重命名失败 " << old_path << ": " << ec.message() << std::endl; ec.clear(); } else { std::cout << old_path << " 已成功重命名为 " << new_path << std::endl; } } std::getchar(); return 0; }
编译这个版本的时候需要注意部分编译器要加filesystem链接参数,比如GCC需要加-lstdc++fs,Clang需要加-lc++fs。
可选优化点
如果不想硬编码文件数量,可以加遍历当前目录的逻辑,自动匹配所有符合img (*) - Copy.jpg格式的文件,自动提取序号生成目标文件名,不用手动调整数量适配实际文件数。
内容的提问来源于stack exchange,提问作者Hmmjon
相关产品推荐
相关产品推荐

