1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| #include <iostream> #include <string> #include <filesystem> #include <windows.h>
namespace fs = std::filesystem;
void inputCheck(int argc, char* argv[] , char* envp[]) { if (argc != 4) { std::cerr << "Usage: " << argv[0] << " <directory_path> <new_prefix> <need_suffix>" << std::endl; } }
void dirCheck(fs::path dirPath) { if (!fs::exists(dirPath) || !fs::is_directory(dirPath)) { std::cerr << "错误:路径不存在或不是目录。" << std::endl; } }
int renamefile(fs::path dirPath, std::string newPrefix, std::string needSuffix) { int count = 0; try { for (const auto& entry : fs::directory_iterator(dirPath)) { if (entry.is_regular_file() && entry.path().extension().string() == needSuffix) { fs::path oldPath = entry.path(); fs::path newPath = oldPath.parent_path() / (newPrefix + std::to_string(count+1) + oldPath.extension().string()); fs::rename(oldPath, newPath); std::cout << "Renamed: " << oldPath.filename().string() << " -> " << newPath.filename().string() << std::endl; count++; } } } catch(const std::filesystem::filesystem_error& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } std::cout << "Total files renamed: " << count << std::endl; return 0; }
int main(int argc, char* argv[] , char* envp[]) {
inputCheck(argc, argv, envp) ; fs::path dirPath(argv[1]); std::string newPrefix(argv[2]); std::string needSuffix(argv[3]); dirCheck(dirPath); renamefile(dirPath, newPrefix, needSuffix);
return 0; }
|