我尝试编写在当前目录及其子目录中查找所有文件的应用程序。我有下一个问题我无法完全理解
- 在我的情况下我需要如何使用递归
GetFiles()
函数,以及 - 我需要在
PathCreator()
函数中动态分配的空闲内存。当我仅针对某些目录(没有子目录)测试该程序时,它可以工作(查看 中的注释代码_tmain()
)。但是当我尝试获取所有文件时,就会崩溃。
这是我的代码:
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
#include <iostream>
#define SIZE 300
int is_directory(wchar_t *p)
{
wchar_t temp[300];
int i;
i = 0;
while(*p != '\0')
{
temp[i] = *p;
p++;
i++;
}
temp[i] = '\\';
i++;
temp[i] = '\0';
WIN32_FIND_DATA file;
HANDLE search_hendle = FindFirstFile(temp, &file);
long error = GetLastError();
if(error == 267)
{
return 0;
}
else
{
return 1;
}
}
wchar_t *PathCreator(wchar_t *dir, wchar_t *fileName)
{
wchar_t* path = new wchar_t[SIZE];
int j = 0;
while(j < SIZE)
{
path[j] = '\0';
j++;
}
int i;
i = 0;
while(*dir != '*' && *dir != '\0')
{
path[i] = *dir;
i++;
dir++;
}
wchar_t *t = fileName;
while(*t != '\0')
{
path[i] = *t;
i++;
t++;
}
path[i] = '\0';
return path;
}
wchar_t* allFlsArr[SIZE];
int i = 0;
wchar_t **GetAllFiles(wchar_t* dir)
{
WIN32_FIND_DATA file;
HANDLE search_hendle = FindFirstFile(dir, &file);
if(search_hendle)
{
do
{
wchar_t *p = PathCreator(dir,file.cFileName);
allFlsArr[i++] = p;
}
while(FindNextFile(search_hendle, &file));
allFlsArr[i] = '\0';
}
CloseHandle(search_hendle);
return allFlsArr;
}
void GetFiles(wchar_t *dir)
{
wchar_t **filePaths = 0;
filePaths = GetAllFiles(dir);
int i = 0;
while(filePaths[i] != '\0'){
if(!is_directory(filePaths[i]))
{
std::wcout << filePaths[i] << std::endl;
}
else
{
GetAllFiles(filePaths[i]);
}
}
delete [] filePaths;
}
int _tmain(int argc, _TCHAR* argv[])
{
/*wchar_t **wch = GetAllFiles(L"C:\\*");
int i = 0;
while( *wch != '\0')
{
std::wcout << *wch << std::endl;
wch++;
}*/
GetFiles(L"C:\\*");
}