1. 程式人生 > >批量修改圖片名 C++

批量修改圖片名 C++

#include <iostream>
#include<Windows.h>
#include <io.h>  //進行系統檔案操作的標頭檔案  
#include <sstream>//格式轉換,這裡是int轉為string  
#include <string>
#include<TCHAR.h>


using namespace std;
const int N = 3;//假如少於100張,N=2,則編號1~99;N=3,則編號01~099,N=4,則編號0001~0099  
const string fileType = ".png";//需要重新命名圖片的格式  
string int2string(int n, int i);//型別轉換函式
string GetExePath();//獲取當前exe的路徑
void string_replace(string &strBig, const string &strsrc, const string &strdst);
void HandleFile(string FileName, string strSrc, string strDst);


int main(int argc,char *argv[])
{
cout << endl << "argc = " << argc << endl;
cout << "Command line arguments received are:" << endl;
for (int i = 0; i < argc; i++)
{
cout << "argument " << (i + 1) << ": " << argv[i] << endl;
}
string FileName = argv[1];;//存放圖片的資料夾
string strSrc = argv[2];//被替換的字串
string strDst = argv[3];//替換的字串
HandleFile(FileName, strSrc, strDst);


system("pause");
return 0;
}






string GetExePath()
{
char szFilePath[MAX_PATH + 1] = { 0 };
GetModuleFileNameA(NULL, szFilePath, MAX_PATH);
(strrchr(szFilePath, '\\'))[0] = 0; // 刪除檔名,只獲得路徑字串  
string strPath ;


for (int n = 0; szFilePath[n]; n++)
{
if (szFilePath[n] != _T('\\'))
{
strPath += szFilePath[n];
}
else
{
strPath += _T("\\");
}
}
return strPath;


}


void string_replace(string &strBig, const string &strsrc, const string &strdst)
{
string::size_type pos = 0;
string::size_type srclen = strsrc.size();
string::size_type dstlen = strdst.size();


while ((pos = strBig.find(strsrc, pos)) != std::string::npos)
{
strBig.replace(pos, srclen, strdst);
pos += dstlen;
}
}


string int2string(int n, int i)//型別轉換函式  
{
char s[BUFSIZ];
sprintf_s(s, "%d", i);
int len = strlen(s);
if (len > n)
{
cout << "輸入的N太小!";
}
else
{
stringstream Num;
for (int i = 0; i < n - len; i++)
Num << "0";
Num << i;


return Num.str();
}
}


void HandleFile(string FileName, string strSrc, string strDst)
{
_finddata_t file;   // 查詢檔案的類  
string fileDirectory = GetExePath()+"\\" + FileName;//當前程式路徑
string buffer = fileDirectory +"\\*" + fileType;
//long hFile;//win7系統  
intptr_t hFile;//win10系統  
hFile = _findfirst(buffer.c_str(), &file); //找第一個檔案  


if (hFile == -1L)
cout << "沒有指定格式的圖片" << endl;//沒有指定格式的圖片  
else
{
int i = 0;
string newFullFilePath;
string oldFullFilePath;
string strName;
do
{
oldFullFilePath.clear();
newFullFilePath.clear();
strName.clear();


oldFullFilePath = fileDirectory + "\\" + file.name;
//++i;
//strName = int2string(N, i); //型別轉換
string strName = file.name;
string_replace(strName, strSrc, strDst);//替換字串
newFullFilePath = fileDirectory + "\\" + strName;


int c = rename(oldFullFilePath.c_str(), newFullFilePath.c_str());//重新命名  
if (c == 0)
cout << "重新命名成功" << strName << endl;
else
cout << "重新命名失敗" << strName << endl;


} while (_findnext(hFile, &file) == 0);
_findclose(hFile);
}
return;
}