Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C Linux
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 1-Apr-13 12:02pm
(unknown member)
Comments
Sergey Alexandrovich Kryukov at 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

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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;
}
  Permalink  
Comments
Maciej Los at 2-Apr-13 3:30am
   
+5 for self-resolved ;)
Sabri Mev at 2-Apr-13 8:10am
   
:)

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

  Print Answers RSS
0 George Jonsson 215
1 Kornfeld Eliyahu Peter 169
2 OriginalGriff 120
3 PIEBALDconsult 110
4 Zoltán Zörgő 99
0 OriginalGriff 6,165
1 DamithSL 4,658
2 Maciej Los 4,107
3 Kornfeld Eliyahu Peter 3,649
4 Sergey Alexandrovich Kryukov 3,342


Advertise | Privacy | Mobile
Web02 | 2.8.141220.1 | Last Updated 2 Apr 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100