C++中采用正则方式获取目录下文件的规范名字
2017-03-21 11:20
211 查看
背景:
获取目录下的文件名,但是由于文件名命名不规范统一,需要从文件名中提取出特定的信息作为该文件名的新名称,以实现文件的重命名。分析:
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);//
相关文章推荐
- 获取c++执行文件的当前目录
- C++ 如何获取目录下面的文件/文件的创建时间
- 采用上下文获取应用程序文件目录
- 采用非递归方式遍历目录及其子目录的文件
- 【Unix编程】C/C++获取目录下文件或目录
- 列出目录下所有文件包括子目录的文件路径-采用递归方式
- [C/C++标准库]_[初级]_[获取文件的所在目录跨平台实现]
- C++获取文件夹下所有文件名称的三种方式
- C/C++ 获取目录下的文件列表信息
- Java从不同目录获取文件方式
- C++、WIN API、MFC分别遍历文件夹、获取文件名称的三种方式【耿然原创】
- Linux学习之路--获取某目录下的所有文件的名字(包括路径)
- C++获取一个目录下的所有文件
- C/C++--C++获取目录下的文件列表
- C++ 如何获取目录下面的文件/文件的创建时间
- [eclipse使用]采用直接copy plugins和features文件夹到eclipse目录方式安装pdt文件失败的问题
- c++学习之获取目录下的文件列表
- 采用正则表达式获取文本文件中的特定模式字符串
- 【Unix编程】C/C++获取目录下文件或目录
- [C/C++]_[初级]_[使用C字符串(或者std::string)处理函数获取文件所在目录