Click here to Skip to main content
11,716,133 members (87,539 online)
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 11:02am
Sabri M746
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 Sergey Alexandrovich Kryukov 683
1 Richard MacCutchan 280
2 Maciej Los 259
3 OriginalGriff 160
4 F-ES Sitecore 135
0 Sergey Alexandrovich Kryukov 1,003
1 Richard MacCutchan 430
2 CHill60 415
3 Maciej Los 399
4 OriginalGriff 385


Advertise | Privacy | Mobile
Web03 | 2.8.150901.1 | Last Updated 2 Apr 2013
Copyright © CodeProject, 1999-2015
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