c++实现windows下批量修改文件名程序

工作中要批量修改文件数量一多就随手写了段代码,有时间再做成一个“软件”完善点功能。
这段代码的功能是将指定目录(子目录)下所有文件名中的"@2x"字符串去掉。
这里的搜索方式和目标文件的判断十分简单,若要做成工具还需严谨一些。
比如文件名包含N次XXX字符串的,要替换的到底是哪一个。
目标文件的文件扩展名可以是哪些?这里没有处理。
ps:
rename(const char* oldName, const char* newName)这里用的是完整的绝对路径。

#include <windows.h>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <iostream>
#include <algorithm>

using namespace std;

const char flagStr[] = "@2x";

void fun(string rootPath)
{
	map<string, string> result;
	queue<string> directory;
	WIN32_FIND_DATA fileData;
	HANDLE hFindFile;
	//strcat_s(nextFile->path, "*.*");
	directory.push(rootPath);
	while (!directory.empty())
	{
		string forderPath = directory.front();
		rootPath = forderPath;
		directory.pop();
		forderPath += "*.*";
		hFindFile = ::FindFirstFile(forderPath.c_str(), &fileData);
		if(hFindFile != INVALID_HANDLE_VALUE)
		{
			do 
			{
				if(fileData.cFileName[0] == '.')continue;
				if(fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
				{
					string tempStr = rootPath + string(fileData.cFileName) + "\\";
					directory.push(tempStr);
				}
				else
				{
					string fileName = fileData.cFileName;
					int pos = fileName.find(flagStr);
					if(pos != -1)
					{
						string changeName = fileName;
						changeName.erase(pos, 3);
						result.insert(make_pair(rootPath + fileName, rootPath + changeName));
					}
				}
			} while(::FindNextFile(hFindFile, &fileData));
		}
	}
	for(map<string, string>::iterator it = result.begin(); it != result.end(); ++it)
	{
		cout << it->first << " " << it->second << endl;
		rename(it->first.c_str(), it->second.c_str());
	}
}

int main()
{
	fun("C:\\Users\\cyj\\Desktop\\Instance\\");
	getchar();
	return 0;
}

  

posted @ 2013-10-06 20:37  oathKeeper  阅读(2710)  评论(0编辑  收藏  举报