1

I am trying to traverse through a directory whose path is given but the following program is not going inside the directories and is stuck in infinit loop. What is the problem in this code:

void func(char path[]);
int main(int argc, char *argv)
{
    char buf[255];
    getcwd(buf,255);
    func(buf);
}

void func(char path[])
{
    DIR *dirp;
    struct stat states;
    struct dirent *direntp;

    dirp=opendir(path);
    chdir(path);

    while((direntp=readdir(dirp))!=NULL)
    {
        if(S_ISDIR(states.st_mode))//true than returns zero
        {
            printf("%s\n",direntp->d_name);
        }
    else
        if(!(strcmp(direntp->d_name,".")||strcmp(direntp->d_name,"..")))// if true retrns zero
        {   
            continue;
        }
        else
        {
            func(direntp->d_name);
            chdir("..");
        }
    }
}
akira
  • 6,050
  • 29
  • 37
Alfred
  • 1,543
  • 7
  • 33
  • 45

3 Answers3

1

You're either missing some code or the issue is the fact that you never populate/update states.

Also have another look at this line:

if(!(strcmp(direntp->d_name,".")||strcmp(direntp->d_name,"..")))

It will never evaluate to a true value as that would require the direntp->d_name to be equal to . and .. at the same time (which is simply impossible). I guess you wanted to check with a && here, which would only enter the branch in case your directory name matches either value.

Mario
  • 35,726
  • 5
  • 62
  • 78
  • Sorry that was a typing mistake ! is for the whole comparison – Alfred Dec 13 '12 at 08:50
  • Not sure I can follow you. You negate the result of the logical or - that's how I read it? – Mario Dec 13 '12 at 08:52
  • @Alfred From DeMorgan's Law `!(a || b) == !a && !b`. In your case it will be true only if both `strcmp()` return 0 which is impossible (string must be equal to `"."` and `".."` at the same time). – Archie Dec 13 '12 at 09:14
  • Mario is right. You should have a call as below to update state of states: if(stat(currentPath, &states) == -1){ perror("stat"); return errno; } – O.C. Dec 14 '12 at 08:10
0

In this piece of your code, states is not initialized before it is used:

struct stat states;
struct dirent *direntp;

dirp=opendir(path);
chdir(path);

while((direntp=readdir(dirp))!=NULL)
{
    if(S_ISDIR(states.st_mode))//true than returns zero

I think compiler would warn about that, too, so please switch on warning in your compiler (-W -Wall for gcc), and then heed and fix the warnings.

hyde
  • 60,639
  • 21
  • 115
  • 176
0

You can check whether if the node is directory without an auxiliary states.struct dirent has a field called d_type, AND it with DT_DIR to test if it is a directory.

MYMNeo
  • 818
  • 5
  • 9