做数据标注的时候,当有的数据没有标注,最后整理的时候需要剔除掉没有标注的数据,所以整理了一下C++的删除不同名文件的代码
大佬勿喷,还请指导一下
#include <io.h>
#include <string>
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
vector<string> Get_File_Name(string dir)
{
//目标文件夹路径
std::string otherPath = dir;
//用于查找的句柄
intptr_t handle1;
struct _finddata_t fileinfo1;
vector<string> fileName;
//第一次查找
handle1 = _findfirst(otherPath.c_str(), &fileinfo1);
if (handle1 == -1)
{
cout << "查找失败" << endl;
}
do
{
string str = fileinfo1.name;//文件名
size_t found = str.find_last_of(".");//查找“.”
string str1 = str.substr(0, found);//相当于去除后缀
fileName.push_back(str1);//存入Vector
} while (!_findnext(handle1, &fileinfo1));
_findclose(handle1);
return fileName;
}
/*匹配并且保存 参数:1:数量少的文件夹,2:数量多的文件夹,3:数量多的文件夹*/
void Match_And_Save(string dir1, string dir2,string dir3)
{
vector<string>fileNames;//保存匹配的文件名称
fileNames = Get_File_Name(dir1);//接收文件名
intptr_t handle;
struct _finddata_t fileinfo;
//第一次查找
handle = _findfirst(dir2.c_str(), &fileinfo);
if (handle == -1)
{
cout << "查找失败" << endl;
}
int i=0,j = 0;
do
{
string str = fileinfo.name;
size_t found = str.find_last_of(".");
string str1 = str.substr(0, found);
if (fileNames[i].compare(str1) != 0)//数量少的文件夹下的文件名是否与数量多的文件夹下的文件名相等
{
j++;
string f_Path = dir3 + str;
string comd = "del " + f_Path;
cout << f_Path << "---这是找到的第 " << j << " 个文件名未能匹配的文件";
cout << "------该文件已经删除"<<endl;
system(comd.c_str());//删除
}
else
{
i++;
}
} while (!_findnext(handle, &fileinfo));
_findclose(handle);
cout << "\n该文件夹下总共:" << i+j << "个文件!!!" << endl;
cout << "\n总共找到 " << j << " 个不匹配文件!.........成功删除所有不匹配文件!!!" << endl;
cout << "\n该文件夹下剩余:" << i << "个文件!!!" << endl;
}
int main()
{
string small_Dir_Path = "F:\\jinglingbiaozhu\\yuanlin\\*.txt";//数量少的文件夹
string big_Dir_Path = "F:\\jinglingbiaozhu\\deal\\*.png";//数量大的文件夹
string root_Path = "F:\\jinglingbiaozhu\\deal\\";
Match_And_Save(small_Dir_Path, big_Dir_Path,root_Path);
return 0;
}