EvilZone

Programming and Scripting => C - C++ => : colton August 11, 2014, 03:46:20 AM

: [C] FileSearch
: 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.

: (c)
#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;
}
: Re: [C] FileSearch
: s3my0n August 14, 2014, 11:53:51 AM
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.
: Re: [C] FileSearch
: Sherlock Holmes August 17, 2014, 03:20:42 PM
CodeBlocks gives error on line 43..


C:\CodeBlocks\FileSearch\main.c|43|error: 'struct dirent' has no member named 'd_type'
: Re: [C] FileSearch
: Kulverstukas August 17, 2014, 09:53:03 PM
dirent is probably an external lib which you need to link.
: Re: [C] FileSearch
: institute August 18, 2014, 06:46:46 AM
You can get the dirent.h here, http://softagalleria.net/dirent.php.


Just drop it in your includes.
: Re: [C] FileSearch
: kenjoe41 September 04, 2014, 06:14:03 PM
And i thought dirent.h is a unix header. Correct me if it actually works on windows.
: Re: [C] FileSearch
: TheWormKill September 04, 2014, 09:54:08 PM
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' ^^.
: Re: [C] FileSearch
: Sherlock Holmes September 14, 2014, 06:57:01 PM
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....?
: Re: [C] FileSearch
: Kulverstukas September 14, 2014, 09:16:09 PM
Didn't work for me on windows..included the dirent file too...idk..maybe i did something wrong....?
stacktrace pl0x.