查找目录中的文件数 [英] Find the number of files in a directory
问题描述
Linux中是否有任何方法可以计算O(1)中目录(即,直接子目录)中的文件数(独立于文件数)而不必先列出目录?如果不是O(1),有没有一种合理有效的方法?
Is there any method in Linux to calculate the number of files in a directory (that is, immediate children) in O(1) (independently of the number of files) without having to list the directory first? If not O(1), is there a reasonably efficient way?
我正在寻找 ls的替代项| wc -l </ code>。
I'm searching for an alternative to ls | wc -l
.
推荐答案
readdir并不像您想象的那样昂贵。诀窍是避免统计每个文件,并(可选)对ls的输出进行排序。
readdir is not as expensive as you may think. The knack is avoid stat'ing each file, and (optionally) sorting the output of ls.
/ bin / ls -1U | wc -l </ code>
/bin/ls -1U | wc -l
在您的shell中避免使用别名,不对输出进行排序,并且每行列出1个文件(并非绝对必要)
avoids aliases in your shell, doesn't sort the output, and lists 1 file-per-line (not strictly necessary when piping the output into wc).
最初的问题可以改写为目录的数据结构是否存储条目数的计数?答案是否定的。没有比readdir(2)/ getdents(2)更有效的文件计数方法。
The original question can be rephrased as "does the data structure of a directory store a count of the number of entries?", to which the answer is no. There isn't a more efficient way of counting files than readdir(2)/getdents(2).
这篇关于查找目录中的文件数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!