0

One of the issues I've encountered whilst making a recursive directory lister is that a call after a directory check isn't invoked in the recursive function's stack.

void direct_crawl(int indent, char *cwd, STAT nstat)
{
    int i, i_in, count;
    struct direct **files;
    int file_comp();

    count = scandir(cwd, &files, file_comp, alphasort);

    for (i = 0; i < count; i++)
    {
       for (i_in = 0; i_in < indent; i_in++)
            printf("\t");
       printf("%s\n", files[i]->d_name);

       stat(files[i], nstat);

       if (S_ISDIR(nstat->st_mode) != 0)
            direct_crawl(indent + 1, files[i]->d_name, nstat)
     }

}

it goes up ONE subdirectory, but if those directories have subdirectories it just doesn't bother...so, could someone please explain what I'm doing wrong? thanks.

x86ris
  • 61
  • 1
  • 5

1 Answers1

0

What you're doing wrong is that even in subdirectories you call stat() with just a filename, which is searched in the current directory and not in the subdirectory, so stat() fails. It may work if you call chdir(cwd) before and chdir("..") after the for loop.

Armali
  • 18,255
  • 14
  • 57
  • 171
  • Better yet, build (e.g. with `asprintf` or `snprintf`) the complete name of the file. But always skip `.` & `..` entries. And you should use `nftw` – Basile Starynkevitch Oct 24 '14 at 12:08