Linux下的文件遍历和Windows下的文件遍历示例

来源:互联网 发布:淘宝刷运费险 编辑:程序博客网 时间:2024/06/06 01:42
来自:http://blog.163.com/tiger_zl2005/blog/static/56329720072141332843/


1.Linux下的目录遍历函数
 int num=0;
 int i=0;
 int j = 0;
 int k=0;
 int dir_len=0;
    int m=0;
    char temp[MAX_PATH_LEN]; 
 struct dirent **namelist ;
 struct stat statbuf = {0};
 
 char dir[200] = "./";
 char Pattern[200] = "";
 
 if(path == NULL)
  return FALSE;
 num = scandir(path, &namelist, 0, alphasort);
 if(-1 != num)
 {
  /*Get Directory*/
  for(i = 0; i < num; i++)
  {
   if(!strcmp(namelist[i]->d_name,".")||!strcmp(namelist[i]->d_name,".."))        
   {
    continue;
   }  
   sprintf(dir,"%s/%s",path,namelist[i]->d_name);
   if(-1 != stat(dir, &statbuf))
   {
    if(S_ISDIR(statbuf.st_mode))
    {
      对应的目录处理过程
      递归调用自己实现广度遍历  }
 
    }
    else
    {
        对文件的处理过程   


    }


 }
2.Windows下的目录遍历函数 


 
 struct _finddata_t filefind;
 char curr[MAX_PATH_LEN]; 
 char xing[]="*.*";
 int  done = 0,m=0;  
 int  handle;
 int  i = 0;
 
 strcpy(curr,path);
 strcat(curr,"\\*.*");
 
 if((-1) ==(handle = _findfirst(curr,&filefind)))
 {
  return FALSE;
 }
 while(!(done = _findnext(handle,&filefind)))
 {
  if(!strcmp(filefind.name,".")||!strcmp(filefind.name,".."))
  {
   continue;
  }
  
  if (_A_SUBDIR & filefind.attrib)
  {    


      对应的目录处理过程
      递归调用自己实现广度遍历  }
  else 
  { 
   对文件的处理过程  


   }    
 }
 _findclose(handle);   
#endif


 


需要用到目录遍历的朋友请不要忘了添加头文件<dirent.h>到你的头文件中


参考网络资料 其基本实现代码如下


 


DIR *pDir;
 struct dirent *findfile;
 struct stat subDir;


 pDir=opendir(searchPath);
 
 if (pDir == NULL)
 {
  return -1 ;
 }


 do
 {
  if(!strcmp(findfile->d_name,".") || !strcmp(findfile->d_name,".."))
  {
   continue;
  }


    if (stat(searchPath, &subDir) != -1 )
  {
   if ( S_ISDIR( subDir.st_mode) )
   {
      if(strcmp(findfile->d_name,"Word") == 0)
    {
     return 1;
    }




    }
   else
   {




   }
  }
  
 }while(( findfile = readdir( pDir ) ) != NULL);


 closedir(pDir);

原创粉丝点击