C++批量修改文件名字

为了实验方便,需要为实验数据文件的名字添加一些标注。为了方便地添加或修改文件名标注,所以写了这个程序。

实验数据来自CMU Graphics Lav Motion Capture Database。

其中的文件名为:01_01.amc, 前两位是两个数字,代表这条运动数据的表演者。然后是下划线。接着又是两个数字,代表这个表演者表演的第几个运动。文件格式是amc。

由于一些原因,会导致文件名后边会多出一些我们不想要的内容,我们要将这部分删掉。同时,我们希望在这些文件名后边加上一些标注,例如,将01_01.amc变为01_01_run.amc,方便我们直接从名字就能知道这条数据的内容。

思路是读取一个文件夹,读取下边的文件,读取每一个文件的名字,然后保存进一个vector中。然后遍历这个文件名vector,挨个修改名字。

#include <iostream>
#include <string>
#include <io.h>
#include <stdlib.h>
#include <vector>
using namespace std;

string dirpath = "E:\\gmmbayestb-v1.0\\motionData\\clusterData\\walk\\";

int main()
{
	_finddata_t file;
	long lf;
	char suffixs[] = "*.amc";          //要寻找的文件类型
	vector<string> fileNameList;   //文件夹下.amc类型文件的名字向量
	char *p;
	p = (char *)malloc((dirpath.size()+1)*sizeof(char));
	strcpy(p, dirpath.c_str());

	//获取文件名向量
	if ((lf = _findfirst(strcat(p, suffixs), &file)) ==-1l)
	{
		cout<<"文件没有找到!\n";
	} 
	else
	{
		cout<<"\n文件列表:\n";
		do {
			cout<<file.name<<endl;
			//str是用来保存文件名的字符串string
			string str(file.name);          
			fileNameList.push_back(str);           
			cout<<endl;
		}while(_findnext(lf, &file) == 0);
	}
	_findclose(lf);

	//遍历文件名向量,并进行修改
	string strAdd = "_walk.amc";   //在原文件名的基础上要增加的部分
	for (vector<string>::iterator iter = fileNameList.begin(); iter != fileNameList.end(); ++iter)      
	{
		string oldName = dirpath+*iter;
		//str1为原文件名要保留的部分
		string str1;
		str1 = (*iter).substr(0,5);
		string newName = dirpath+str1+strAdd;
		cout<<"oldName:"<<oldName<<endl;
		cout<<"newName"<<newName<<endl;

		cout<<"oldName size = "<<oldName.size()<<endl;
		cout<<"newName size = "<<newName.size()<<endl;
		
		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());
		cout<<oldNamePointer<<endl;
		cout<<newNamePointer<<endl;

		rename(oldNamePointer, newNamePointer);

		free(oldNamePointer);
		free(newNamePointer);
	}
	system("PAUSE");
	return 0;
}



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值