# simplest file search

This is a discussion on simplest file search within the Windows Programming forums, part of the Platform Specific Boards category; Hi I am looking for a simple program that goes thru the directory tree to find a file. No MFC ...

1. ## simplest file search

Hi
I am looking for a simple program that goes thru the directory tree to find a file. No MFC and other stuff, just plain Win32 development.

Thnx a lot

2. Under File Management Functions:
FindFirstFile()

Under Path Functions:
PathFindFileName
PathFindOnPath()

Of course, you may have to use these functions recursively (or in a loop) to search subdirectories. Here is a code snippet from a simple find function I created:

Code:
/* calling routine */
...
/* call find on some directory */
find("C:\some\directory\to\start\from");
...
...

void find(const char *rootPath)
{
char searchTerm[strlen(rootPath)+3];
strcpy(searchTerm, rootPath);
strcat(searchTerm, "\*");

WIN32_FIND_DATA fd;
HANDLE hFind = FindFirstFile(searchTerm, &fd);
if(hFind == INVALID_HANDLE_VALUE)
return;
do
{
/* if its a subdirectory, call find again */
if(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY &&
strcmp(fd.cFileName , ".")!=0 && strcmp(fd.cFileName , "..")!=0)
{
char subPath[strlen(rootPath) + strlen(fd.cFileName) + 2];
strcpy(subPath, rootPath);
strcat(subPath, "\");
strcat(subPath, fd.cFileName);
find(subPath);
}
else
{
/* do some other stuff its a file */
}
}
while(FindNextFile(hFind, &fd));
FindClose(hFind);
}

3. You mean like the many examples in the FAQ then

4. Thanks.

A small question:
will char searchTerm[strlen(rootPath)+3];
compile? Should be a constant expression, shouldn't it?

ole

5. Yes it should be a constant expression.

6. Originally Posted by ole111
Thanks.
A small question:
will char searchTerm[strlen(rootPath)+3];
compile? Should be a constant expression, shouldn't it?
It's fine if you're using a C99 compliant compiler (which is pretty much any decent compiler).