MoistyTacos
MoistyTacos

Reputation: 13

Searching through all sub directories within a directory

So I had help and now I have a program that searches through the current directory and prints out the file if it exists, now how would I make it so that it goes through a different directory and searches for the file in all the sub directories of it?

I thought if I replaced the line "." with "..", it would go back to the previous directory and go thought all the sub directories, but it only looks for the file in the directory without going in the subs.

//headers here

char  *FINDME=NULL;

int filter (const struct dirent *p){
  int retval=0;
if (fnmatch(FINDME,p->d_name, 0) == 0)
  retval = 1;
return retval;
}

int main(int argc, char **argv){
    struct dirent **namelist;
    int i = 0;

    FINDME = (argc > 1) ? argv[1] : "testfilename";
    i = scandir("..", &namelist, filter, alphasort);

    if(i < 0){
            perror("scandir");
            exit(1);
    }

    while(i--){
            printf("%s\n", namelist[i]->d_name);
            free(namelist[i]);
    }
    free(namelist);

    return 0;
}

Upvotes: 0

Views: 94

Answers (2)

mcleod_ideafix
mcleod_ideafix

Reputation: 11428

Travelling through a filesystem is actually travelling through a tree (excluding hard and symlinks), so you can use the recursive way:

The following pseudocode will give you an idea:

Function TravelDirectory (String dirname, String filename)
  Foreach item=Element in dirname Do
    If item.type is File AND item.name==filename
      Print item
    Else If item.type is Directory
      TravelDirectory (item.name, filename)
  EndFor
EndFunction

To implement this in C under Linux, for example, you can use the opendir()and readdir() functions instead of scandir(). readdir() will serve you as an iterator for the Foreach part.

Upvotes: 1

jhoffman
jhoffman

Reputation: 95

Im not 100% certain but have you tried a wildcard or adding a trailing slash

You have ..

Try ../ OR ../*

Upvotes: 0

Related Questions