A quick way to find the number of files in a single directory on Linux

I am looking for a quick way to find the number of files in a directory on Linux.

Any decision that takes linear time in the number of files in a directory is NOT acceptable (for example, "ls | wc -l", etc.), because it takes too much time (there are dozens or maybe hundreds of millions files in the directory).

I am sure that the number of files in a directory should be stored as a prime somewhere in the file system structure (perhaps inode?), As part of the data structure used to store entries in a directory - how can I get to this number?

Edit: The file system is ext3. If there is no portable way to do this, I am ready to do something specific for ext3.

+3
source share
5 answers

Why should the data structure contain a number? A tree does not need to know its size in O (1), unless this is a requirement (and ensuring this may require more blocking and possibly a performance bottleneck)

By tree, I do not mean including the contents of subdir, but files with -maxdepth 1 - suppose that they really are not stored in the list.

edit: ext2 saved them as a linked list.

modern ext3 implements hashed B-Trees

Having said that, / bin / ls does a lot more than counting and actually scans all inodes. Write your own C program or script using opendir () and readdir ().

:

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main()
{
        int count;
        struct DIR *d;
        if( (d = opendir(".")) != NULL)
        {
                for(count = 0;  readdir(d) != NULL; count++);
                closedir(d);
        }
        printf("\n %d", count);
        return 0;
}
+6

inotify . , , .

+2

Inode , . inode (st_nlink - ).

, , . , ls.

, , B-.

+1

. , .. readdir, . , . .

0

, , "repquota".

0

Source: https://habr.com/ru/post/1755354/


All Articles