一、这两个函数均在io.h里面。
二、首先了解一下一个文件结构体:
struct _finddata_t {
unsigned attrib;
time_t time_create;
time_t time_access;
time_t time_write;
_fsize_t size;
char name[260];
};
time_t,其实就是long
而_fsize_t,就是unsigned long
现在来解释一下结构体的数据成员吧。
attrib,就是所查找文件的属性:_A_ARCH(存档)、_A_HIDDEN(隐藏)、_A_NORMAL(正常)、_A_RDONLY(只读)、 _A_SUBDIR(文件夹)、_A_SYSTEM(系统)。
time_create、time_access和time_write分别是创建文件的时间、最后一次访问文件的时间和文件最后被修改的时间。
size:文件大小
name:文件名。
三、用 _findfirst 和 _findnext 查找文件
1、_findfirst函数:long _findfirst(const char *, struct _finddata_t *);
第一个参数为文件名,可以用"*.*"来查找所有文件,也可以用"*.cpp"来查找.cpp文件。第二个参数是_finddata_t结构体指针。若查找成功,返回文件句柄,若失败,返回-1。
void dfsFolder(string folderPath, vector<string> &filenames)
{
_finddata_t FileInfo;
string strfind = folderPath + "\\*";
long Handle = _findfirst(strfind.c_str(), &FileInfo);
if (Handle == -1L)
{
cerr << "can not match the folder path" << endl;
exit(-1);
}
do {
//判断是否有子目录
if (FileInfo.attrib & _A_SUBDIR)
{
//这个语句很重要
if ((strcmp(FileInfo.name, ".") != 0) && (strcmp(FileInfo.name, "..") != 0))
{
string newPath = folderPath + "\\" + FileInfo.name;
dfsFolder(newPath, filenames);
}
}
else
{
string newPath = folderPath + "\\" + FileInfo.name;
filenames.push_back(newPath);
cout << folderPath.c_str() << "\\" << FileInfo.name << endl;
}
} while (_findnext(Handle, &FileInfo) == 0);
_findclose(Handle);
}
这个时候测试的时候会在第29行while (_findnext(Handle, &FileInfo) == 0);处报错,错误信息为
经过查阅资料发现在x64环境下编译的话, _findfirst 还有 _findnext 则不能使用,会报错。
代码修改为:
void dfsFolder(string folderPath, vector<string> &filenames)
{
__finddata64_t FileInfo;
string strfind = folderPath + "\\*";
__int64 Handle = _findfirst64(strfind.c_str(), &FileInfo);
if (Handle == -1L)
{
cerr << "can not match the folder path" << endl;
exit(-1);
}
do {
//判断是否有子目录
if (FileInfo.attrib & _A_SUBDIR)
{
//这个语句很重要
if ((strcmp(FileInfo.name, ".") != 0) && (strcmp(FileInfo.name, "..") != 0))
{
string newPath = folderPath + "\\" + FileInfo.name;
dfsFolder(newPath, filenames);
}
}
else
{
string newPath = folderPath + "\\" + FileInfo.name;
filenames.push_back(newPath);
cout << folderPath.c_str() << "\\" << FileInfo.name << endl;
}
} while (_findnext64(Handle, &FileInfo) == 0);
_findclose(Handle);
}
即在3、5、29行分别使用匹配64位的函数即可。
最后成功在vector中存入了所有的文件名。