批量重命名文件
Posted 鹅要长大
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了批量重命名文件相关的知识,希望对你有一定的参考价值。
前言
实现代码的过程中经常需要将文件夹中的所有文件进行重命名,以方便对文件进行处理。
实现过程
1.测试代码;
/************************************************************************ * Copyright(c) 2017 AMY * All rights reserved. * * File: * Brief: * Version: 1.0 * Author: * Email: [email protected] * Date: 2017/10/27 * History: * 20171027: ; ************************************************************************/ //------------------------------------------------------------------------- #include <iostream> #include <string> #include <vector> #include "opencv2/opencv.hpp" #include "opencv2/contrib/contrib.hpp" using namespace std; int main() { string oldFolder = "E:\\fatigue_detection\\dataset\\img\\"; string oldType = "*.jpg"; bool addPath = true; cv::Directory dir; vector<string> filenames = dir.GetListFiles(oldFolder, oldType, addPath); string newName; string oldName; string newType = ".png"; for (int i = 0; i < filenames.size(); i++) { oldName = filenames[i]; newName = oldFolder + to_string(i) + newType; ////method1 //char *oldNamePointer, *newNamePointer; //oldNamePointer = (char *)malloc((oldName.size() + 1) * sizeof(char)); //newNamePointer = (char *)malloc((newName.size() + 1) * sizeof(char)); //strcpy(oldNamePointer, oldName.c_str()); //strcpy(newNamePointer, newName.c_str()); //rename(oldNamePointer, newNamePointer); //free(oldNamePointer); //free(newNamePointer); ////method2 char* oldNamePointer = new char[(oldName.size() + 1) * sizeof(char)]; char* newNamePointer = new char[(oldName.size() + 1) * sizeof(char)]; strcpy(oldNamePointer, oldName.c_str()); strcpy(newNamePointer, newName.c_str()); rename(oldNamePointer, newNamePointer); delete [] oldNamePointer; delete [] newNamePointer; } return 0; }
注意,不同类型之间的转换,比如char*和string、const char*和string等.
2.c++中new和delete的使用;
2.1)针对实体:
type_name * point_name = new type_name; delete type_name;
注意,只能使用delete来释放使用new分配的内存;使用delete的关键在于只用于new分配的内存即new的地址.
2.2)针对动态数组:
type_name * point_name = new type_name [num_elements]; delete [] type_name;
注意,数组使用的是方括号[];
2.3)使用new和delete应遵守的规则:
- 不要使用delete来释放不是new分配的内存;
- 不要使用delete释放同一个内存块两次;
- 如果使用new [] 为数组分配内存,则应使用delete [] 来释放;
- 如果使用new为一个实体分配内存,则应使用delete(没有方括号)来释放;
- 对空指针使用delete是安全的;
参考
1.here
2.书籍:c++ Primer Plus.
完
以上是关于批量重命名文件的主要内容,如果未能解决你的问题,请参考以下文章