#include <iostream>
#include <string>
#include <string.h>
#ifdef _WIN32
#include <io.h>
#else
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#endif
using namespace std;
static bool Findfile(string filepath,string keyword,string&file)
{
#ifdef _WIN32
struct _finddata_t filefind;
memset(&filefind,0,sizeof(_findata_t));
string curr = filepath + "\\*.*";
intptr_t handle = _findfirst(curr.c_str(),&filefind);
if(handle==-1)return false;
__time64_t filetime = 0;
while((0==_findnext(handle,&filefind)))
{
if(!strcmp(filefind.name,".")||!strcmp(filefind.name,".."))
continue;
if(strstr(filefind.name,keyword.c_str())&&filetime<filefind.time_creat)
{
filetime = filefind.time_creat;
file = filepath+"/"+filefind.name;
}
}
_findclose(handle);
#else
struct dirent* ptr = 0;
DIR *pDir = opendir(filepath.c_str());
if(!pDir)
return false;
time_t filetime = 0;
while((ptr = readdir(pDir))!=0)
{
if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0))
continue;
string temp = filepath+"/"+ptr->d_name;
struct stat buf = {0};
stat(temp.c_str(),&buf);
if(strstr(ptr->d_name,keyword.c_str())&& (filetime<buf.st_mtime))
{
file = temp;
filetime = buf.st_mtime;
}
}
closedir(pDir);
#endif
if(filetime)return true;
else return false;
}
int main()
{
string filepath;
if(Findfile("E:\\temp","con",filepath))
cout<<filepath<<endl;
else
cout << "not find";
return 0;
}
函数说明:跨平台的文件查找,根据关键字查找当前文件夹下的所有文件中最新的一个文件路径返回。
结构体说明:
stat():用于获取文件的状态信息,使用时需要包含<sys/stat.h>头文件。
函数原型:int stat(const char *path, struct stat *buf);
struct stat
{
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for file system I/O */
blkcnt_t st_blocks; /* number of 512B blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last status change */
}
struct _finddata_t
{
unsigned attrib; //文件的属性信息,例如_A_ARCH 存档,_A_HIDDEN 隐藏,_A_SUBDIR 文件夹等
time_t time_create; //文件创建时间
time_t time_access; //文件最后被访问的时间
time_t time_write; //文件最后被改写的时间
_fsize_t size; //文件的大小
char name[MAX_FNAME]; //文件名称
};
struct dirent
{
__ino_t d_ino; /*inode number 索引节点号*/
__off_t d_off; /*offset to this dirent 在目录文件中的偏移*/
unsigned short int d_reclen; /*length of this d_name 文件名长*/
unsigned char d_type; /*the type of d_name 文件类型*/
char d_name[256]; /*file name(null-terminated) 文件名 */
};