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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With