说明:C++访问文件夹中的内容没有python方便,这里做一下记录,提供实现访问文件夹内容并删除指定类型文件的接口。
应用场景:删除某一文件夹中上次生成的文件,防止下次生成时,没有将上次生成的文件完全覆盖,即个数<上次。
#include <iostream>
#include <string>
#include <vector>
#include <windows.h>
//删除上次生成的包含子串subStr的文件
bool removeSavedfile(std::string strNamePath, std::string subStr)
{
string inPath = strNamePath+'*';
intptr_t handle;
struct _finddata_t fileinfo;
//第一次查找
handle = _findfirst(inPath.c_str(), &fileinfo);
if (handle == -1)
return false;
do
{
string::size_type idx;
string Str = static_cast<std::string>(fileinfo.name);
idx = Str.find(subStr);//在长串中查找子串.
if (idx != string::npos)// 存在
{
string NamePath = strNamePath + Str;
const char* strName = NamePath.c_str();
remove(strName);
}
//找到的文件的文件名
//std::cout << fileinfo.name << std::endl;
//printf("%s\n", fileinfo.name);
} while (!_findnext(handle, &fileinfo));
_findclose(handle);
return true;
}
struct _finddata_t结构体如下:
struct _finddata_t
{
unsigned attrib;
time_t time_create;
time_t time_access;
time_t time_write;
_fsize_t size;
char name[_MAX_FNAME];
};