【编程语言】C++ 对指定的目标文件重命名

C++遍历指定目录下的文件,并对其重命名

代码如下

#include <string>
#include <vector>
#include <iostream>
#include <direct.h>
#include <io.h>
#include <stdio.h>
#include <sstream>

using namespace std;

void f_get_samples_path(string& s_images_path,vector<string>& v_images_path);
void f_sample_rand(string& s_images_path,vector<string>& v_images_path,string& s_format);

int main()
{	
	string s_images_path_positive="../roi/"; //文件所在目录路径
	string s_format="jpg"; //修改后的文件后缀
	vector<string> v_images_path; //存放指定目录下的文件路径
	f_get_samples_path(s_images_path_positive,v_images_path); 
	f_sample_rand(s_images_path_positive,v_images_path,s_format);
	system("pause");
	return 0;
}

void f_sample_rand(string& s_images_path,vector<string>& v_images_path,string& s_format)
{
	int i_flag; //随机函数返回标记s
	string s_filename_old; //要修改的文件名
	string s_filename_new; //修改后的文件名
	int i_count=0; //统计总共执行多少次
	for(int i=0;i<v_images_path.size();i++)
	{
		stringstream ss_randstring;
		ss_randstring<<rand(); //将int 转成 string
		s_filename_old=v_images_path[i]; //要修改的文件名
		s_filename_new=s_images_path+ss_randstring.str()+"."+s_format; //修改后的文件名
		ss_randstring.clear(); //清空字符串流

		cout<<"s_filename_old"<<s_filename_old<<endl;
		cout<<"s_filename_new"<<s_filename_new<<endl;

		i_flag=rename(s_filename_old.c_str(),s_filename_new.c_str()); //通过rand()对目标文件重命名
		if (i_flag==0) 
		{
			cout<<"文件:"<<"--"<<s_filename_old<<"--"<<"修改成功!"<<endl;					
		}
		else
		{
			cout<<"文件:"<<"--"<<s_filename_old<<"--"<<"修改失败!"<<"失败编号:"<<i_flag<<endl;
		}
		i_count++;
	}
	cout<<"总共执行次数:"<<i_count<<endl;
}



运行结果



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值