Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Searching for files and folders 2

Status
Not open for further replies.

Leibnitz

Programmer
Apr 6, 2001
393
CA
How do i search for files and folders in a specific directory without using any MFC code,any hint will be very apreciated.
 
#define WIN32_LEAN_AND_MEAN
#include <iostream>
#include <windows.h>

int main()
{

WIN32_FIND_DATA FindFile;
HANDLE hFile;

if ( ( hFile = FindFirstFile( &quot;C:\\TempHold\\*.txt&quot;,&FindFile ) ) ==
INVALID_HANDLE_VALUE )
{
std::cout << &quot;Invalid File Handle.&quot; <<
std::endl;
exit( 0 );
}

do {

std::cout << FindFile.cFileName <<
std::endl;

} while ( FindNextFile( hFile,&FindFile ) );

return 0;

}

The code above uses the raw Win32 API to search for files in a particular directory. FindFirstFile() coupled with FindNextFile() will return all text files ( as denoted by the *.txt wildcard ) in the C:\TempHold folder on my disk. You can change this wildcard to a filename to search for that file in the folder. If that file is not in the directory in question, then &quot;Invalid File Handle&quot; will be displayed on the console. Mike L.G.
mlg400@blazemail.com
 
how about if you want it to display folders?
 
Replace the wildcard in FindFirstFile() with *.*

hFile = FindFirstFile( &quot;C:\\*.*&quot;,&FindFile ) ) ==
INVALID_HANDLE_VALUE ) Mike L.G.
mlg400@blazemail.com
 
#define WIN32_LEAN_AND_MEAN
#include <iostream>
#include <windows.h>

int main()
{
WIN32_FIND_DATA FindFile;
HANDLE hFile;

if ( ( hFile = FindFirstFile( &quot;C:\\*.*&quot;,&FindFile ) ) ==
INVALID_HANDLE_VALUE )
{
std::cout << &quot;Invalid File Handle.&quot; <<
std::endl;
exit( 0 );
}

do {

if ( FindFile.dwFileAttributes ==
FILE_ATTRIBUTE_DIRECTORY )
{
std::cout << FindFile.cFileName <<
std::endl;
}

} while ( FindNextFile( hFile,&FindFile ) );

return 0;
}

The above code will only display the directories located in C:\ Mike L.G.
mlg400@blazemail.com
 
I forgot to mention that there is also alot of information that you can extract from the handle that you pass to FindFirstFile(),FindNextFile() i.e. creation time,alternate file name, file size etc... Mike L.G.
mlg400@blazemail.com
 
Thank you very much LiquidBinary,i had search for this for a long time in the web but did not find anything interesting till now.
 
How can i display all subdirectories as well ?
 
Do not forget, plese:
hFile = FindFirstFile( &quot;C:\\*.*&quot;,&FindFile );
...
FindClose(hFile);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top