EvilZone
Programming and Scripting => C - C++ => : colton August 11, 2014, 03:46:20 AM
-
Here's an example of file search using the dirent.h, it works well. Way faster then the built in Windows 7 search... I was impressed and found this on accident.
#include <stdio.h>
#include <dirent.h>
#include <time.h>
int FileSearch(char* szPath, char* szSearch);
int main( int argc, char* argv[])
{
clock_t b, s;
b=clock();
if (argc != 3) {
fprintf(stderr, "Usage: FileSearch <directory> <search/term>\r\n");
}
FileSearch(argv[1], argv[2]);
s=clock();
printf("Elapsed: %f seconds\n", (double)(s - b) / CLOCKS_PER_SEC);
return 0;
}
int FileSearch(char* szPath, char* szSearch)
{
struct dirent* entry;
char szBuffer[260];
DIR *dir;
if ((dir = opendir(szPath)) == NULL) {
return 1;
}
while ((entry = readdir(dir)))
{
if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0)
{
sprintf_s(szBuffer, sizeof(szBuffer), "%s%s", szPath, entry->d_name);
if (S_ISDIR(entry->d_type)) {
strcat_s(szBuffer, "\\");
FileSearch(szBuffer, szSearch);
}
if (strstr(entry->d_name, szSearch)) {
printf("Found match: %s\r\n", szBuffer);
}
}
}
closedir(dir);
return 0;
}
-
Can be faster if instead of recursion you use iteration. Can also crash if there's too many nested directories - runs out of stack space.
-
CodeBlocks gives error on line 43..
C:\CodeBlocks\FileSearch\main.c|43|error: 'struct dirent' has no member named 'd_type'
-
dirent is probably an external lib which you need to link.
-
You can get the dirent.h here, http://softagalleria.net/dirent.php.
Just drop it in your includes.
-
And i thought dirent.h is a unix header. Correct me if it actually works on windows.
-
Just adding something that might be important:
If you use optimization (which is a probably good idea in this specific case if we're talking about performance), many compilers will convert recursive structures to loops if possible. Just sayin' ^^.
-
And i thought dirent.h is a unix header. Correct me if it actually works on windows.
Didn't work for me on windows..included the dirent file too...idk..maybe i did something wrong....?
-
Didn't work for me on windows..included the dirent file too...idk..maybe i did something wrong....?
stacktrace pl0x.