背景:
获取目录下的文件名,但是由于文件名命名不规范统一,需要从文件名中提取出特定的信息作为该文件名的新名称,以实现文件的重命名。
分析:
1:采用readdir来获取目录下文件
2:采用regexec对文件名进行正则匹配,获取文件名中的hash信息作为该文件的新名称
3:注意旧文件名中由于hash只是文件名的一部分,可能存在相同hash信息,需要对此做处理。
代码:
string hashfile="hash_list.txt";
string Src="krc/";
ofstream hashList(hashfile.c_str());
vector<string> files;
string hashtemp;
vector<string> songmidVec;
DIR *dir;
struct dirent *ptr;
dir = opendir(Src.c_str()); //open the dir
regex_t m_HashReg;
int rc = regcomp(&m_HashReg, "\\w{32}", REG_EXTENDED|REG_NEWLINE);
while((ptr = readdir(dir)) != NULL) ///read the list of this dir
{
#ifdef _WIN32
printf("d_name: %s\n", ptr->d_name);
#endif
#ifdef __linux
if(ptr->d_type == 8)//只要文件名
{
hashtemp = ptr->d_name;
size_t dotPosi = hashtemp.rfind(".");
std::string hashtemp_1 = hashtemp.substr(0,dotPosi);
//通过正则方式获取hash
const char *indexstart = NULL;
const char *indexend = NULL;
const int nr_match = 4;
regmatch_t matches[nr_match];
rc = regexec(&m_HashReg, hashtemp_1.c_str(), nr_match, matches, 0);
std::string new_hash;
if(rc == 0)
{
indexstart = hashtemp_1.c_str() + matches[0].rm_so;
indexend = hashtemp_1.c_str() + matches[0].rm_eo;
new_hash.append(indexstart,indexend);//get each line's time
if(new_hash.size()!=32)
{
printf("error hash:%s\n",new_hash.c_str());
continue;
}
}
else if(rc == REG_NOMATCH)
{
printf("match failed!\n");
continue;
}
else
{
printf("unknow error\n");
continue;
}
printf("d_type:%d d_name: %s\n", ptr->d_type,hashtemp_1.c_str());
vector<string>::iterator unitsongmidIter = find(files.begin(), files.end(), new_hash);
if(unitsongmidIter == files.end())
{
files.push_back(new_hash);
hashList<<new_hash<<std::endl;
string path1_original;
path1_original = Src + hashtemp;
string path1 = "new_krc/" +new_hash+".krc" ;
rename(path1_original.c_str(),path1.c_str());//如果源文件和目标文件不在同一个文件夹下则实现的是文件的移动和重命名
}
}
#endif
}
hashList.close();
closedir(dir);
string hashdir= hashfile;
ifstream Inputread(hashdir.c_str());
regfree(&m_HashReg);//