Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I efficiently retrieve the number of files in a directory?

Is there a way (on windows using Delphi 2010) to get the number of files in a dirctory without actually traversing all files?

I want to implement a progress bar during some file system indexing operation. For that reason I need to know how many files are in the directory.

What is the fastest way to get the number of files in a directory?

like image 404
jpfollenius Avatar asked Oct 30 '09 10:10

jpfollenius


People also ask

How do we get the count of number of files in a directory?

Browse to the folder containing the files you want to count. Highlight one of the files in that folder and press the keyboard shortcut Ctrl + A to highlight all files and folders in that folder. In the Explorer status bar, you'll see how many files and folders are highlighted, as shown in the picture below.

How do you get files count in a directory in Linux?

The easiest way to count files in a directory on Linux is to use the “ls” command and pipe it with the “wc -l” command. The “wc” command is used on Linux in order to print the bytes, characters or newlines count. However, in this case, we are using this command to count the number of files in a directory.

How do I list the number of files in a directory in Python?

Getting a count of files of a directory is easy as pie! Use the listdir() and isfile() functions of an os module to count the number of files of a directory.


2 Answers

If you are running on Windows 7 or Server 2008 R2, I recommend extracting the FindFirst and FindMatchingFile functions from SysUtils and hacking the former to use FindFirstFileEx instead of FindFirstFile. Then you can set the additional flags parameter to 2 (defined in MSDN as FIND_FIRST_EX_LARGE_FETCH) with this setting conditioned on (Win32majorversion = 6) and (Win32minorversion >= 1), for the time being.

This setting produces a very significant speed increase for FindFirst/FindNext loops on these OS. Look for FindFirstFileEx on MSDN for more details, as the latest documentation is not in the Microsoft documentation retrieved by Delphi help.

TDirectory.GetFiles eventually seems to call FindFirst, so will not buy you much advantage other than simplifying your own code.

like image 117
frogb Avatar answered Nov 09 '22 10:11

frogb


I think the fastest way is to use the TDirectory.GetFiles method located in IOutils.pas. As the number of (visible) files in a directory may be different for each user, there is only a tiny chance that there is just a number to retrieve somehow.

The FindFirst/FindNext approach (which is wrapped in the above method) doesn't actually traverse files, it only traverses entries in a table, so it might be faster than expected.

like image 24
Uwe Raabe Avatar answered Nov 09 '22 11:11

Uwe Raabe