findfirst,、findnext 、_findfirst、 _findnext搜索磁盘目录
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <string>
#include <io.h>
#include <direct.h>
using namespace std;
#if 0
struct _finddata_t
{
unsigned attrib;
time_t time_create;
time_t time_access;
time_t time_write;
_fsize_t size;
char name[260];
};
attrib的参数:
_A_ARCH(存档)
_A_HIDDEN(隐藏)
_A_NORMAL(正常)
_A_RDONLY(只读)
_A_SUBDIR(文件夹)
_A_SYSTEM(系统)
int _findnext(intptr_t handle, struct _finddata_t *fileinfo);
搜索与_findfirst函数提供的文件名称匹配的下一个实例,若成功则返回0,否则返回-1
long _findfirst(char *filespec, struct _finddata_t *fileinfo); 否则返回 - 1L
搜索与指定的文件名称匹配的第一个实例,若成功则返回第一个实例的句柄,
_access(char *); 判断文件或文件夹路径是否合法 <direct.h>
_chdir(char *); 设置当前目录<direct.h>
#endif
void Find(string sPath)
{
_finddata_t file;
memset(&file, 0, sizeof(file));
long hFile;
string sPathLast = sPath;
if (_chdir(sPathLast.c_str())!= 0)
{
cerr << "当前目录设置失败!" << endl;
exit(-1);
}
hFile = _findfirst("*", &file); //*代表查找所有
if (hFile == -1)
{
cout << "遍历失败!" << endl;
return;
}
while (_findnext(hFile, &file) == 0)
{
if (file.name[0] == '.') //过滤本级目录和父级目录
continue;
if (file.attrib == _A_SUBDIR) //子文件夹
{
string sAddPath = sPath;
sAddPath += "\\";
sAddPath += file.name;
cout << "目录:" << sAddPath << endl;
Find(sAddPath); //递归遍历查找
}
else
{
string sAddPath = sPath;
sAddPath += "\\";
sAddPath += file.name;
cout << "文件:" << sAddPath << endl;
}
}
_findclose(hFile); //关闭文件句柄
}
int main()
{
string sPath = "D:\\FlashFXP";
Find(sPath);
return 0;
}