glibc 遞歸遍歷文件夾 dfs_search_file

dfs_search_file




#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>

int dfs_search_file (const char *dir)
{
  DIR *dp;
  struct dirent *ep;
  struct stat statbuf;
  
  dp = opendir (dir);
  if (dp != NULL)
    {
	    while ((ep = readdir (dp))!=NULL)
	    {
	        if(ep->d_type==4) 
	        {//is dir
	      		if (strcmp(ep->d_name , ".")==0 || strcmp(ep->d_name , "..")==0)
	      		//if (ep->d_name[strlen(ep->d_name)-1]=='.')
	      		{
	      			continue;
	      		}
	      		//
	      		char * tmp = (char *)malloc(sizeof(char) * (strlen(ep->d_name) + strlen(dir)+2 ));
	      		strcpy(tmp,dir);
	      		strcat(tmp,"/");
	      		strcat(tmp,ep->d_name);
	      		//
		        //puts (ep->d_name);
	      		dfs_search_file(tmp);
	      		free(tmp);
	      	}
	      	else if(ep->d_type==8) 
	      	{
	      		char * tmp = (char *)malloc(sizeof(char) * (strlen(ep->d_name) + strlen(dir)+2 ));
	      		strcpy(tmp,dir);
	      		strcat(tmp,"/");
	      		strcat(tmp,ep->d_name);
		        printf("%s\n", tmp);
		        free(tmp);
	      	}
      	}
      	(void) closedir (dp);
    }
    else
    {
    	perror ("Couldn't open the directory");
  	}

  return 0;
}



int main(int argc, char const *argv[])
{
	dfs_search_file("/home");
	return 0;
}






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