編寫 find

編寫find

刺蝟@http://blog.csdn.net/littlehedgehog






去年做的一個小搜索是win32的,這次回頭看看windows SDK的代碼,不得不承認windows 在API的設計上封裝的很複雜,unix上邏輯上很清晰的代碼在windows上看得有些讓人摸不着頭腦。


  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <dirent.h>
  4. #include <sys/stat.h>
  5. #include <sys/types.h>
  6. int check_dir(char *filename)
  7. {
  8.     struct stat file_info;
  9.     if(stat(filename,&file_info)!=-1)
  10.     {
  11.         if(S_ISDIR(file_info.st_mode))
  12.             return 1;
  13.     }
  14.     return 0;
  15. }
  16. void search_file(char *dir_name,char *target)
  17. {
  18.     char filename[64];
  19.     DIR *dir_ptr;
  20.     struct dirent *dirent_ptr;
  21.     if((dir_ptr=opendir(dir_name))!=NULL)
  22.     {
  23.         while((dirent_ptr=readdir(dir_ptr))!=NULL)
  24.         {
  25.             if(strcmp(dirent_ptr->d_name,".")&&strcmp(dirent_ptr->d_name,".."))
  26.             {
  27.                 strcpy(filename,dir_name);
  28.                 strcat(filename,"/");
  29.                 strcat(filename,dirent_ptr->d_name);
  30.                 strcat(filename,"/0"); 
  31.                 if(strstr(filename,target))
  32.                     printf("%s/n",filename);
  33.                 if(check_dir(filename))
  34.                     search_file(filename,target);   
  35.             }
  36.         }   
  37.         closedir(dir_ptr);
  38.     }
  39.     else
  40.     {   
  41.         sprintf(stderr,"Cannot open the file %s:",dir_name);
  42.         perror(""); 
  43.     }
  44. }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章