C++纯WinAPI实现遍历目录下的所有文件

话不多说,直接上代码。

#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <bits/stdc++.h>
using namespace std;
long cnt=0;
void viewfiles(char *directory)
{
    WIN32_FIND_DATA fdFindData;
    HANDLE hFind;
    char *filename;
    int count=0;
    BOOL done;
    filename=new char[strlen(directory)+5];
    strcpy(filename,directory);
    strcat(filename,"\\*.*");
    hFind=FindFirstFile(filename,&fdFindData);
    delete[] filename;
    done=hFind!=INVALID_HANDLE_VALUE;
    while(done)
    {
          if(strcmp(fdFindData.cFileName,".") && strcmp(fdFindData.cFileName,".."))

          {
                filename=new char[strlen(directory)+strlen(fdFindData.cFileName)+2];
                strcpy(filename,directory);
                strcat(filename,"\\");
                strcat(filename,fdFindData.cFileName);
                if((fdFindData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)==FILE_ATTRIBUTE_DIRECTORY) {
                    viewfiles(filename);
                } else {
                	cout << "文件名:" << filename << endl;
                	cnt++;
				}
                delete[] filename;
          }
          done=FindNextFile(hFind,&fdFindData);
    }
    FindClose(hFind);
}

int main() {
	cout << "输入索引名称:" << endl;
	char directory[MAX_PATH];
	gets(directory);
	cout << endl;
	clock_t start_time=clock();
	viewfiles(directory);
	cout << endl;
	printf("\n----------\n遍历完毕!\n统计数据:\n共遍历文件:%ld个\n共用时%.2lf秒\n平均速度:%.2lf个文件/秒\n----------\n", cnt, (double)(clock()-start_time)*1.0/CLOCKS_PER_SEC, cnt / ((double)(clock()-start_time)*1.0/CLOCKS_PER_SEC));
	cin.clear();
	system("pause");
	return 0;
}

本文为作者原创,如果喜欢,请点个赞,谢谢!

posted @ 2020-02-26 08:44  EricNTH  阅读(575)  评论(0编辑  收藏  举报