- 1 year ago
C++ Windows Files Search yielding
To perform a file search in C++ on Windows, you can use the WinAPI functions provided by the Windows operating system. The following example demonstrates how to search for files in a specific directory and its subdirectories:
cpp#include <iostream>
#include <Windows.h>
void SearchFiles(const std::wstring& directory, const std::wstring& pattern)
{
WIN32_FIND_DATAW findData;
HANDLE hFind = INVALID_HANDLE_VALUE;
std::wstring searchPath = directory + L"\\*" + pattern;
hFind = FindFirstFileW(searchPath.c_str(), &findData);
if (hFind == INVALID_HANDLE_VALUE)
{
std::wcout << L"No files found." << std::endl;
return;
}
do
{
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (wcscmp(findData.cFileName, L".") != 0 && wcscmp(findData.cFileName, L"..") != 0)
{
std::wstring subDir = directory + L"\\" + findData.cFileName;
SearchFiles(subDir, pattern);
}
}
else
{
std::wstring filePath = directory + L"\\" + findData.cFileName;
std::wcout << filePath << std::endl;
}
} while (FindNextFileW(hFind, &findData) != 0);
FindClose(hFind);
}
int main()
{
std::wstring directory = L"C:\\path\\to\\directory";
std::wstring pattern = L"*.txt";
SearchFiles(directory, pattern);
return 0;
}
In this example, the SearchFiles
function recursively searches for files in the specified directory
and its subdirectories using the provided pattern
. It uses the FindFirstFileW
, FindNextFileW
, and FindClose
functions from the Windows API to perform the file search.
To use this code, replace "C:\\path\\to\\directory"
with the actual directory path you want to search, and "*.txt"
with the desired file search pattern. For example, you can search for all text files by using "*.txt"
, or all files by using "*.*"
.
Compile and run the program, and it will print the paths of the matching files found in the specified directory and its subdirectories.