Click here to Skip to main content
15,894,410 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am trying to get the number of directories in a directory but I cannot get the real result. If there are 5 files in directory and 2 of them are directories, I get 'y' 5 but It must be 2.
x= isdirectory(dirp); I am not sure whether I send the corrent thing to the function.Thanks in advance.

int listFilesIndir(char *currDir) //Lists files in directory
{
    struct dirent *direntp;
    DIR *dirp;
    int x ,y =0 ;


    if ((dirp = opendir(currDir)) == NULL) 
    {
        perror ("Failed to open directory");
        return 1;
    }

    while ((direntp = readdir(dirp)) != NULL)
    {
        printf("%s\n", direntp->d_name);
        x= isdirectory(dirp); //I dont not know what I should send to the function 
                              // to check if its directory or not? it must 
                              // be 'dirp' or 'd_name'? what?
        if(x != 0)
            y++;
    }
    printf("direc Num : %d\n",y );

    while ((closedir(dirp) == -1) && (errno == EINTR)) ;

    return 0;
}


int isdirectory(char *path) 
{
    struct stat statbuf;

    if (stat(path, &statbuf) == -1)
        return 0;
    else 
        return S_ISDIR(statbuf.st_mode);
}
Posted
Comments
Sergey Alexandrovich Kryukov 1-Apr-13 18:53pm    
Looks simple. Did you run it under the debugger? Chances are, isdirectory returns non-zero all the time.
—SA

1 solution

I have found the problem .Now It works great. The if statemenet is updated.
int listFilesIndir(char *currDir) 
{
    struct dirent *direntp;


    DIR *dirp;
    int x ,y =0 ;


    if ((dirp = opendir(currDir)) == NULL) 
    {
        perror ("Failed to open directory");
        return 1;
    }

    while ((direntp = readdir(dirp)) != NULL)
    {
        printf("%s\n", direntp->d_name);
        if(direntp->d_type == DT_DIR) //Updated..
            y++;
    }


    printf("direc Num (except parent and curr) : %d\n",y-2 );

    while ((closedir(dirp) == -1) && (errno == EINTR)) ;

    return 0;
}
 
Share this answer
 
Comments
Maciej Los 2-Apr-13 3:30am    
+5 for self-resolved ;)
[no name] 2-Apr-13 8:10am    
:)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900