简介
不知道大家有没有遇到这样的情况:手机上和电脑上都用pixiv下载过图片,但是把文件放在一起时文件名的格式不一样。手机上下载的图片文件名格式是“illust_xxxxx_xxxx.jpg”之类,而电脑上是“xxxxx_p0.jpg”。这样子有没有重复下载就需要一个一个去翻,而知道pid找自己有没有图也要麻烦一些,因为文件的排序是按照文件名的。于是我写了一个批量修改文件名的程序,供大家参考。这个程序可以将形如“illust_xxxxx_xxxxx.xxx”的文件名转换为“xxxxxx_px.xxx”的格式,而且会自动生成后缀p1、p2、p3……。如果有什么错的地方烦请联系我修改。
主要是三个函数:getFiles、getPath和modify_name,分别用来获取文件夹内文件、分离文件路径和获取新名称。依靠STL string和标准库sstream,以及rename函数实现。其中getFiles参考这位大佬的博客。详细看下面的代码好了。
使用方法
很简单,只要输入文件夹的绝对路径即可。注意要用“”来分隔而不是“/”。千万不要输错!
可以先拿几张图片测试一下。
不保证本程序没有bug。
如果failed,尝试重新运行程序。如果还是failed,检查一下是不是改完就重名了。再不行的话右上角联系我吧。
源码
可能需要按照自己的需要适当修改
modify.cpp:
#include <iostream>
#include <io.h>
#include "modify.h"
using namespace modify;
using std::cin;
using std::cout;
using std::endl;
vector<string> files;
int main(int argc, char const *argv[]) {
string file_path = "D:\\111";
string fp;
cin >> file_path;
getFiles(file_path.data(), files);
string new_name;
for (register int i = 0, e = files.size(); i != e; ++ i) {
new_name = modify_name(files[i]);
fp = getPath(files[i]);
if (new_name.length() == 0) continue;
new_name.insert(0, fp);
int result = rename(files[i].data(), new_name.data());
if (result == 0) {
cout << "succeeded:" << endl << files[i] << endl;
}
else
cout << "faild:" << endl << files[i] << endl;
}
return 0;
}
modify.h:
#pragma once
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
namespace modify{
using std::stringstream;
using std::string;
using std::unordered_map;
using std::vector;
unordered_map<string, unsigned int> map1;
string modify_name(string old_name) {
string appender;
static stringstream strstream;
unsigned int i1 = old_name.find("illust_");
if (i1 == 0xffffffff) return string();
old_name.erase(0, i1 + 7);
unsigned int i2 = old_name.find('_');
unsigned int i3 = old_name.find('.');
string extension = old_name.substr(i3, old_name.length() - 1);
old_name.erase(i2, old_name.length() - 1);
string t2 = old_name;
strstream << "_p" << map1[t2] << extension;
map1[t2] = map1[t2] + 1;
strstream >> appender;
old_name.append(appender);
strstream.clear();
return old_name;
}
string getPath(string name) {
unsigned int i = 0xffffffff;
string path;
while ((i = name.find("\\")) != 0xffffffff) {
path.append(name.substr(0, i + 1));
name.erase(0, i + 1);
}
return path;
}
void getFiles( string path, vector<string>& files )
{
//文件句柄
intptr_t hFile = 0;
//文件信息
struct _finddata_t fileinfo;
string p;
if((hFile = _findfirst(p.assign(path).append("\\*").c_str(),&fileinfo)) != -1)
{
do
{
//如果是目录,迭代之
//如果不是,加入列表
if((fileinfo.attrib & _A_SUBDIR))
{
if(strcmp(fileinfo.name,".") != 0 && strcmp(fileinfo.name,"..") != 0)
getFiles( p.assign(path).append("\\").append(fileinfo.name), files );
}
else
{
files.push_back(p.assign(path).append("\\").append(fileinfo.name) );
}
}while(_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}
}
下载
提取码: 7v22