1

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;
}
Sabri Meviş
  • 2,231
  • 1
  • 32
  • 38
  • have you traced the code with a debugger? Does it even enter the recursive portion? – Mike Apr 02 '13 at 12:34

3 Answers3

2

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!   
    }
}
Scy
  • 488
  • 3
  • 11
1

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").

Fabio Ceconello
  • 15,819
  • 5
  • 38
  • 51
0

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).

Kupto
  • 2,802
  • 2
  • 13
  • 16