I’m working on a C++ project in Visual Studio and I’m having trouble with a directory search function. The code works fine at first but crashes when I try to close the file handle.
Here’s my directory searching function:
wstring DirectoryScanner::LocateTargetDirectory(const wstring& startPath, wstring targetDirName)
{
wstring resultDir = L"";
wstring searchPath = startPath + L"\\*";
WIN32_FIND_DATAW fileData;
HANDLE hFind = FindFirstFileW(searchPath.c_str(), &fileData);
if (hFind != INVALID_HANDLE_VALUE)
{
vector<wstring> subdirectories;
do
{
if (fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if ((!lstrcmpW(fileData.cFileName, L".")) || (!lstrcmpW(fileData.cFileName, L"..")))
continue;
}
wstring currentPath = startPath + L"\\" + wstring(fileData.cFileName);
if (fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (fileData.cFileName == targetDirName)
{
resultDir = fileData.cFileName;
return resultDir;
}
subdirectories.push_back(currentPath);
}
} while (FindNextFileW(hFind, &fileData));
CloseHandle(hFind);
for (auto it = subdirectories.begin(); it != subdirectories.end(); ++it)
LocateTargetDirectory(*it, targetDirName);
}
return resultDir;
}
The function starts running normally but when it reaches the CloseHandle line, I get this error:
Exception at 0x76D712C7 in MyApp.exe: 0xC0000008: An invalid handle was specified.
My project setup includes a static library with this class and a console application that uses it. Some of the folder names contain Cyrillic characters but I don’t think that’s causing the issue. What could be wrong with my handle management and how do I fix this problem?