Search code examples
clinuxunixsystems-programming

How can I searches files in current dir and the files in directories that under current dir?


The function searches the files in current directory. If It accrosses a directory, It gets in and again searches for file except the current '.' and the previous '..' directory. But It doesnt work how I want.It does not get in the next directory.

int foo(char *currDir) 
{
  struct dirent *direntp;
  DIR *dirp;
  char currentDir[250];



  if ((dirp = opendir(currDir)) == NULL) 
  {
      perror ("Failed to open directory");
      return 1;
  }

  //By Sabri Mev at GYTE

  while ((direntp = readdir(dirp)) != NULL)
  {
    printf("%s\n", direntp->d_name);
    if(direntp->d_type == DT_DIR)
    {
        if(strcmp(direntp->d_name,".") !=0  && strcmp(direntp->d_name,"..") != 0)
            foo(direntp->d_name); //Recursive!   
    }
  }
  getcwd(currentDir,250);
  printf("curr Dir : %s\n",currentDir );


  while ((closedir(dirp) == -1) && (errno == EINTR)) ;

  return 0;
}

Solution

  • Because your path is error.

    try this

    if(direntp->d_type == DT_DIR)
    {   
        if(strcmp(direntp->d_name,".") !=0  && strcmp(direntp->d_name,"..") != 0) 
        {
            sprintf(currentDir, "%s/%s", currDir, direntp->d_name);
            foo(currentDir); //Recursive!   
        }
    }