How do I search for a filename in c++

Are you writing a program and need to know how to search for a specific file name? After searching around at msdn.microsoft.com and some trial and error I can show you how.  I will be using FindFirstFile and FindNextFile to do my search.First of all you need to include the following libraries in your code:

#include <windows.h>
#include <tchar.h>
#include <stdio.h>

Next you will need to create a handle and a pointer to the WIN32_FIND_DATA  structure that holds any information about the found file or directory.

1
2
WIN32_FIND_DATA FindFileData;
HANDLE hFind;

Then when you are ready to do your search you will need to use FindFirstFile and FindNextFile. They both work hand in hand and are similar to eachother. The handle is returned so that you can keep track of where you have searched. This handle is needed when we use FindNextFile. Also ‘targetFile’ needs to be a cstring.The syntax is as follows:

1
hFind = FindFirstFile(targetFile, &FindFileData);

If your targetFile is a type string class then you will need to convert it using the dot operator .c_str():

1
hFind = FindFirstFile(targetFile.c_str(), &FindFileData);

In order to keep searching you must next use FindNextFile. This is a little different in that it returns a boolean value. You also need to pass in hFind. The syntax is as follows:

1
FindNextFile(hFind, &FindFileData)

Here is an example code that prompts the user for a file or folder to search for. I have it looping on FindNextFile. This will print out the first 30 folders/files if the user puts in a wildcard(Example: C:\Windows\*).  This is just to show the basic concept. You can however, do whatever you would like!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
int main()
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
string targetFile;

cout << "What is the file to be found: ";
getline(cin, targetFile);

hFind = FindFirstFile(targetFile.c_str(), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
cout << targetFile << " was not found. Error " << GetLastError() << endl;
else
{
cout << "The first file found is " << FindFileData.cFileName << endl;
//FindClose(hFind);
}

for (int i = 0; i < 30; i++)
{
if (FindNextFile(hFind, &FindFileData))
{
cout << "The first file found is " << FindFileData.cFileName << endl;
//FindClose(hFind);
}
else
cout << targetFile << " was not found. Error " << GetLastError() << endl;
}

system("PAUSE");
return 1;
}

Leave a Reply

Your email address will not be published. Required fields are marked *