3

Is there anyway to get the total number of files in a specific directory not iterating readdir(3)?

I mean only direct members of a specific directory.

It seems that the only way to get the number of files is calling readdir(3) repeatedly until it returns zero.

Is there any other way to get the number in O(1)? I need a solution that works in Linux.

Thanks.

cinsk
  • 1,576
  • 2
  • 12
  • 14

3 Answers3

0

scandir() example, requires dirent.h:

struct dirent **namelist;
int n=scandir(".", &namelist, 0, alphasort);   //  "."  == current directory.
if (n < 0)
{
    perror("scandir");
    exit(1);
}
printf("files found = %d\n", n);
free(namelist);
jim mcnamara
  • 16,005
  • 2
  • 34
  • 51
  • The `scandir(3)` manpage includes _"The scandir() function scans the directory dirp, calling filter() on each directory entry."_ so no, this will be _O(n)_ and not _O(1)_. I don't think there's an _O(1)_ method for doing this. – Jim Garrison Jun 05 '13 at 04:29
0

I don't think it is possible in O(1). Just think about inode structure. There's no clue for this.

But if it's OK to get number of files in a filesystem, you can use statvfs(2).

#include <sys/vfs.h>    /* or <sys/statfs.h> */
int statfs(const char *path, struct statfs *buf);


struct statfs {
               __SWORD_TYPE f_type;    /* type of file system (see below) */
               __SWORD_TYPE f_bsize;   /* optimal transfer block size */
               fsblkcnt_t   f_blocks;  /* total data blocks in file system */
               fsblkcnt_t   f_bfree;   /* free blocks in fs */
               fsblkcnt_t   f_bavail;  /* free blocks available to
                                          unprivileged user */
               fsfilcnt_t   f_files;   /* total file nodes in file system */
               fsfilcnt_t   f_ffree;   /* free file nodes in fs */
               fsid_t       f_fsid;    /* file system id */
               __SWORD_TYPE f_namelen; /* maximum length of filenames */
               __SWORD_TYPE f_frsize;  /* fragment size (since Linux 2.6) */
               __SWORD_TYPE f_spare[5];
};

You can easily get number of files via f_files - f_ffree.

BTW, This is very interesting question. so I voted it up.

Younggun Kim
  • 938
  • 10
  • 26
-1

In shell script it's damn simple

ll directory_path | wc -l 
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
rahul.deshmukhpatil
  • 977
  • 1
  • 16
  • 31