#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
void findFile(string start)
{
//start 是遍历的目录,如要遍历D盘下test文件夹下的所有文件,那么start = "d:\\test";
string strtemp;
string token = ".";
string tokend = "..";
HANDLE hfile;
WIN32_FIND_DATAA fileDate;//WIN32_FIND_DATA结构描述了一个由FindFirstFile, FindFirstFileEx, 或FindNextFile函数查找到的文件信息
DWORD errorcode = 0;
hfile = FindFirstFileA((start + "\\*.*").c_str() ,&fileDate);
//通过FindFirstFileA()函数,根据当前的文件存放路径查找该文件来把待操作文件的相关属性读取到WIN32_FIND_DATA结构中去
while(hfile!= INVALID_HANDLE_VALUE && errorcode != ERROR_NO_MORE_FILES)
{
strtemp = fileDate.cFileName;
bool flag = false;
if((fileDate.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)&&(strtemp != token)&& (strtemp != tokend))
{
//如果当前文件是目录文件,则递归调用findFile
flag = true;
cout<<strtemp<<" is a direcotry"<<endl;
findFile(start + "\\" + strtemp);
}
else
cout<<strtemp<<endl;//打印文件名
bool isNextFile = FindNextFileA(hfile,&fileDate);//判断该目录下是否还有文件
if(flag == true && isNextFile == true)//如果还有文件,则调用SetLastError,设为NO_ERROR,这样才能继续遍历后面的文件
SetLastError(NO_ERROR);
else
errorcode=GetLastError();
}
}
int main()
{
string start="C:\\Program Files";
findFile(start);
system("pause");
}
findfile
最新推荐文章于 2024-07-22 03:25:07 发布