在一个项目中,遇到了这个需求。
于是windows+vs平台上实现了这个功能Demo。测试完毕后移植到了具体的项目中。
#include <windows.h>
#include <cstdlib>
#include <iostream> // std::cout
#include <algorithm> // std::sort
#include <vector> // std::vector
#include <io.h>
#include <time.h>
using namespace std;
struct FileInfo
{
string fileName;
long long time_write;
static bool LessThan(FileInfo a, FileInfo b)
{
return a.time_write > b.time_write;
}
};
//filePath为文件路径,suffix为后缀名
char* substr(const char*str, unsigned start, unsigned end)
{
unsigned n = end - start;
static char stbuf[512];
//复制最后三个字符,即后缀
strncpy(stbuf, str + start, n);
//字串最后加上0
stbuf[n] = 0;
return stbuf;
}
//判断某文件后缀是否为指定格式
bool decideSuffix(char* filePath, char* suffix)
{
char* fileExt;
char *ptr, c = '.';
//最后一个出现c的位置
ptr = strrchr(filePath, c);
//用指针相减 求得索引
int pos = ptr - filePath;
//获取后缀
fileExt = substr(filePath, pos + 1, strlen(filePath));
//判断后缀是否相同
if (0 == strcmp(fileExt, suffix))
return true;
else
return false;
}
void getFiles(string path, string suffix,unsigned int minFileByteSize, vector<FileInfo>& files)
{
//文件句柄
long hFile = 0;
//文件信息
struct _finddata_t fileinfo;
//
FileInfo tmpFileInfo;
string p,tmp;
p = p.assign(path).append("\\*");
if ((hFile = _findfirst(p.c_str(), &fileinfo)) != -1)
{
do
{
//如果是目录,迭代之,在这里不想迭代
if ((fileinfo.attrib & _A_SUBDIR))
{
/* if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
getFiles(p.assign(path).append("\\").append(fileinfo.name), files);*/
}
else//如果是文件
{
//判断文件后缀是否符合要求
if (decideSuffix(fileinfo.name, (char*)suffix.c_str()))
{
if(fileinfo.size >= minFileByteSize)
{
tmp = tmp.assign(path).append("\\").append(fileinfo.name);
tmpFileInfo.fileName = tmp;
tmp = "";
tmpFileInfo.time_write = fileinfo.time_write;
files.push_back(tmpFileInfo);
}
}
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}
int main()
{
std::string directoryRootPath = "G:\\OSG_MODLE\\";
time_t sttime;
struct tm * tim;
int sec = 0, min = 0, hour = 0, mday = 0, mon = 0, year = 0;
time(&sttime);
tim = localtime(&sttime);
sec = tim->tm_sec; // second (0-61, allows for leap seconds)
min = tim->tm_min; // minute (0-59)
hour = tim->tm_hour; // hour (0-23)
mday = tim->tm_mday; // day of the month (1-31)
mon = tim->tm_mon + 1; // month (0-11)
year = tim->tm_year + 1900; // years since 1900
char newDirectoryName[256] = { 0 };
memset(newDirectoryName, 0, sizeof(newDirectoryName));
sprintf(newDirectoryName, "%04d_%02d_%02d", year, mon, mday);
//最终要查找的目录
string finalDirectoryPath = directoryRootPath + std::string(newDirectoryName);
string suffix = "osg";
vector<FileInfo> filesVec;
getFiles(finalDirectoryPath, suffix,60, filesVec);
//按time_write排序
std::sort(filesVec.begin(), filesVec.end(), FileInfo::LessThan);
char str[30];
int size = filesVec.size();
for (int i = 0; i < size; i++)
{
cout << filesVec[i].fileName.c_str() << endl;
}
getchar();
return 0;
}