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

StackOverflow https://stackoverflow.com/questions/15764149

Вопрос

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;
}
Это было полезно?

Решение

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!   
    }
}

Другие советы

When you do the recursive call to foo() inside the loop, notice that what direntp->d_name contains is not the full path, but just the subdirectory name. You have to concatenate it with currDir and use the result to call foo().

For instance, if you're starting with foo("/home") and the first subdir is "root", you're calling recursively foo("root") when it should be foo("/home/root").

in direntp->d_name you access only the local directory name, it does not return the whole path

also getcwd function is deprecated. Use the ISO C++ conformant _getcwd instead (if you write in C++ off course).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top