您的位置:首页 > 编程语言 > C语言/C++

[C++] 批量删除文件名多余的一个相同字符串

2014-01-27 15:46 633 查看
使用C++方法:

// ++++++++

#include <string>
#include <io.h>
#include <iostream>
using namespace std;
bool change_name(const char* char_path,
const char* char_del)
{
string path="";
string path_main="";
string find_str="";
path.append(char_path);
find_str.append(char_del);

cout<<"Now,you find file path is :"<<path.c_str()<<endl;
path_main.append(path.c_str());
path.append("/*.*");
string path_old="";
string path_new="";
string file_name="";

string find_result="";
string temp_name="";
string file_exe="";
string file_pre="";
_finddata_t file;
bool bFind=false;
bool bFile=false;
long lf;
//输入文件夹路径
if((lf = _findfirst(path.c_str(), &file))==-1)
cout<<"Not Found!"<<endl;
else
{
//输出文件名
cout<<"file name list:"<<endl;
while(_findnext( lf, &file)==0)
{
bFile =false;
bFind =false;
path_old="";
path_new="";
file_name="";
find_result="";
temp_name="";
file_pre="";
file_exe="";
file_name.append(file.name);
path_new.append(path_main.c_str());
path_new.append("\\");
if(file_name.find("..")!= string::npos)
{
continue;
}
//cout<<file.name<<endl;
path_old.append(path_main.c_str());
path_old.append("\\");
path_old.append(file.name);
//cout<<path_old.c_str()<<endl;
int iPos_dot=0;
iPos_dot =file_name.find_last_of(".");
if(iPos_dot<=0)
{
bFile =false;
}
else
{
bFile = true;
}
if(false == bFile)
{
continue;
}
file_exe.append(file_name.substr(iPos_dot,file_name.length()));
temp_name.append(file_name.substr(0,iPos_dot));
int ilen = file_name.length();
int ilen_find = temp_name.length() - find_str.length();
if(temp_name.find(find_str) != string::npos)
{
bFind=true;
}
if(ilen_find>0 && (true==bFind))
{
find_result.append(temp_name.substr(ilen_find,find_str.length()));
file_pre.append(temp_name.substr(0,ilen_find));
if(find_result.find(find_str.c_str())!= string::npos)
{
//cout<<"\r\n find! \r\n"<<endl;
path_new.append(file_pre.c_str());
path_new.append(file_exe.c_str());
cout<<"Old file"<<path_old.c_str()<<endl;
cout<<"New file"<<path_new.c_str()<<endl;
//check path_new if exist?
int access_rs=0;
access_rs = access(path_new.c_str(), 0) ;
if(access_rs == 0)
//if ((fopen(path_new.c_str(),"r"))!=0)
{
cout<<"Files has existed!"<<path_new.c_str()<<endl;
}
else
{
rename(path_old.c_str(),path_new.c_str());
}
}
}
else
{
cout<<"Not find any file!"<<endl;
}
}
}
_findclose(lf);
//cin.get();
return true;
}

void OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
CString sz_Path=_T("");
CString sz_Del=_T("");
GetDlgItemText(IDC_EDIT1,sz_Path);
GetDlgItemText(IDC_EDIT2,sz_Del);
string str_path="";
str_path.append(sz_Path);
cout<<str_path<<endl;
string str_del="";
str_del.append(sz_Del);
change_name(str_path.c_str(),str_del.c_str());
MessageBox("Successfully!",_T("title"),MB_OK);
}

//--------------

在VS2010上面测试没问题
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐