I want to recursively list out file names inside a directory using windows API with desired extension file name.
I have tried out with this but Shlwapi.h seems to be not comfortable with function PathCombine. Could you please let me know if it works at all?
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
#include "Shlwapi.h"
#pragma comment(lib, "User32.lib")
void FindFilesRecursively(LPCTSTR lpFolder, LPCTSTR lpFilePattern)
{
TCHAR szFullPattern[MAX_PATH];
WIN32_FIND_DATA FindFileData;
HANDLE hFindFile;
// first we are going to process any subdirectories
PathCombine(szFullPattern, lpFolder,_T("*"));
hFindFile = FindFirstFile(szFullPattern, &FindFileData);
if(hFindFile != INVALID_HANDLE_VALUE)
{
do
{
if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
// found a subdirectory; recurse into it
PathCombine(szFullPattern, lpFolder, FindFileData.cFileName);
FindFilesRecursively(szFullPattern, lpFilePattern);
}
} while(FindNextFile(hFindFile, &FindFileData));
FindClose(hFindFile);
}
// now we are going to look for the matching files
PathCombine(szFullPattern, lpFolder, lpFilePattern);
hFindFile = FindFirstFile(szFullPattern, &FindFileData);
if(hFindFile != INVALID_HANDLE_VALUE)
{
do
{
if(!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
// found a file; do something with it
PathCombine(szFullPattern, lpFolder, FindFileData.cFileName);
_tprintf_s(_T("%s\n"), szFullPattern);
}
} while(FindNextFile(hFindFile, &FindFileData));
FindClose(hFindFile);
}
}
int main()
{
FindFilesRecursively(_T("E:\\Logstotest"), _T("*.log"));
return 0;
}
Your code works fine if you exclude the direcories named "." and ".." from the search.
The body of your first while loop should look like this :
if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
// Exclude "." and ".." directories
if (_tcscmp(FindFileData.cFileName, _T(".")) != 0 &&
_tcscmp(FindFileData.cFileName, _T("..")) != 0)
{
// found a subdirectory; recurse into it
PathCombine(szFullPattern, lpFolder, FindFileData.cFileName);
FindFilesRecursively(szFullPattern, lpFilePattern);
}
}
The "." directory is the current directory and if you recurse into that you will never get out of recursion, because you will scan the same directory over and over again until the stack is full.
The ".." directory is the directory "above" the current directory and if you scan that you will also run into an infinite recursion for the same reason as stated above.
BTW you can see those directories by using the dir
command in a cmd window.