In specific directory i need to find all files with some specific extension (for example .log) and than save it somewhere. In need only c++ solutions cause i'm trying it on win 2003 server and c++ is my restrictions. Thank you very munch
+2
A:
You can enumerate all of the files in a directory using FindFirstFile
and FindNextFile
(and don't forget to call FindClose
when you're done). You can pass in a filter to these functions to only look for certain filenames, e.g. directory\*.log
.
As you enumerate the files, the WIN32_FIND_DATA
structure that gets returned tells you the filename and attributes of each file (among other things). For each file, check the file attributes to make sure it's a regular file by checking that it has the FILE_ATTRIBUTE_NORMAL
flag so that you ignore directories.
For example:
WIN32_FIND_DATA fileInfo;
HANDLE hFind = FindFirstFile("C:\\directory\\to\\search\\*.log", &fileInfo);
if(hFind == INVALID_HANDLE_VALUE)
; // handle error
else
{
do
{
if(fileInfo.dwFileAttributes & FILE_ATTRIBUTE_NORMAL)
{
printf("Found a .log file: %s\n", fileInfo.cFileName);
}
} while(FindNextFile(hFind, &fileInfo));
if(GetLastError() != ERROR_NO_MORE_FILES)
; // handle error
FindClose(hFind);
}
Adam Rosenfield
2010-09-22 17:31:12
The find functions allow one to specify a mask/filter, so you don't even need to check the extension, just pass "*.log" to FindFirstFile
Necrolis
2010-09-22 17:48:38
@Necrolis: Good point, I've updated my answer and added sample code.
Adam Rosenfield
2010-09-22 18:30:25