How do I get the total number of files in a directory by using C++ standard library?
-
1Directory operation is relative to the OS you're on, unfortunately. So post with what OS you're trying, then perhaps we can better help you. – Daniel May 10 '10 at 12:02
-
Cross platform code to work on both Windows and Linux. I'm using mingw, gcc and msvc along with wxWidgets library, using boost but not linking to its libraries, only including headers. fstat and _stat functions we have in #include
. to get file details. Do we have similar support for getting directory details? – harik May 11 '10 at 04:33
6 Answers
If you don't exclude the basically always available C standard library, you can use that one. Because it's available everywhere anyways, unlike boost, it's a pretty usable option!
An example is given here.
And here:
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main (void)
{
DIR *dp;
int i = 0;
struct dirent *ep;
dp = opendir ("./");
if (dp != NULL)
{
while (ep = readdir (dp))
i++;
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");
printf("There's %d files in the current directory.\n", i);
return 0;
}
And sure enough
> $ ls -a | wc -l
138
> $ ./count
There's 138 files in the current directory.
This isn't C++ at all, but it is available on most, if not all, operating systems, and will work in C++ regardless.
UPDATE: I'll correct my previous statement about this being part of the C standard library - it's not. But you can carry this concept to other operating systems, because they all have their ways of dealing with files without having to grab out additional libraries.
EDIT: : Added initialization of i
-
1-1: The C standard library provides no way to enumerate a directory either. – Billy ONeal May 10 '10 at 13:27
-
7That's a stupid down vote. Of course you can count files using the C standard lib. Take the example I included in my post - instead of calling a "puts ..." inside the while used to iterate over every file, just do "i++" and declare an "int i" somewhere above. There is of course no "directory_get_file_count" function, but that isn't the point. The point is, you CAN use it to get your desired result, namely the amount of files in a folder. The hell, let me edit my original answer with a spoon fed answer, sec – LukeN May 10 '10 at 13:32
-
As for the POSIX part of readdir, that's true, but in windows you have similar functions that I could not test here because I haven't used windows in ages. But the point is: this works in C++, this works in C, you don't need to install special library support and that's what the OP probably wanted. – LukeN May 10 '10 at 13:43
-
5@LukeN: POSIX **is** "special library support". Windows does not have a `
` nor does it have a ` – Billy ONeal May 10 '10 at 14:09`. POSIX is not the C standard library, and your assertion that it is is wrong. -
POSIX yay or nay left aside, one would not simply transfer a C program like this from one operating system to another anyways - all major operating systems have their ways to deal with files and directories. THIS was the Linux example, windows deal with it another way, probably windows.h or something, one can just write some "#ifdef" to handle that and be happy. I'll correct my statement about it being standard C, and just say that those functions will be available wherever such a program would typically run. The asker does not have to install a special library, and that's what counts for me! – LukeN May 10 '10 at 14:19
-
I tend to take things like this to personal, sorry about that. Of course you're right. But I think this is what the poster wanted. Listing files without separatly installing libraries like boost. :) – LukeN May 10 '10 at 14:41
-
1Basically you've now arrived at the comment Daniel made initially: "just use the native OS functions, not a (standard) library". – MSalters May 10 '10 at 15:22
-
-
This solution will not work for me on Windows. I may have to use Boost like libraries for getting required support across platforms. – harik May 11 '10 at 06:04
-
Thanks for the answer, but consider initializing `i` to 0. The code as is invokes undefined behavior. I tried editing it myself but SO requires at least 6 characters of change for an edit (at least with my rep). One of their dumbest rules... – yano Sep 21 '18 at 05:12
You can't. The closest you are going to be able to get is to use something like Boost.Filesystem
EDIT: It is possible with C++17 using the STL's filesystem library

- 41
- 1
- 9

- 54,544
- 15
- 116
- 120
-
6After which it's trivial: `int count = std::difference(directory_iterator(dir_path), directory_iterator());` – MSalters May 10 '10 at 13:39
-
6@MSalters, I can't find any reference to `std::difference`. Are you sure you didn't mean `std::distance`? Also, you'll need a `static_cast
` to coerce `directory_iterator::difference_type` to `int`. – Nathan Ernst May 10 '10 at 15:38 -
I'm trying to avoid linking to Boost libraries and use only headers for algorithms. – harik May 11 '10 at 04:38
-
do we have a way to avoid linking to Boost filesystem library and still get the support for this? – harik May 11 '10 at 06:07
-
@Nathan: of course. @harik: doesn't work; the code you need is in the Boost library. – MSalters May 11 '10 at 06:55
An old question, but since it appears first on Google search, I thought to add my answer since I had a need for something like that.
int findNumberOfFilesInDirectory(std::string& path)
{
int counter = 0;
WIN32_FIND_DATA ffd;
HANDLE hFind = INVALID_HANDLE_VALUE;
// Start iterating over the files in the path directory.
hFind = ::FindFirstFileA (path.c_str(), &ffd);
if (hFind != INVALID_HANDLE_VALUE)
{
do // Managed to locate and create an handle to that folder.
{
counter++;
} while (::FindNextFile(hFind, &ffd) == TRUE);
::FindClose(hFind);
} else {
printf("Failed to find path: %s", path.c_str());
}
return counter;
}

- 77
- 1
- 2
-
To get the number of files in folder *path* you'll have to append path with "\\*" and to eliminate "." and ".." before incrementing counter by checking ffd.cFileName – vess Aug 01 '23 at 17:48
As of C++17 it can be done with STL:
auto dirIter = std::filesystem::directory_iterator("directory_path");
int fileCount = std::count_if(
begin(dirIter),
end(dirIter),
[](auto& entry) { return entry.is_regular_file(); }
);
A simple for-loop works, too:
auto dirIter = std::filesystem::directory_iterator("directory_path");
int fileCount = 0;
for (auto& entry : dirIter)
{
if (entry.is_regular_file())
{
++fileCount;
}
}
See https://en.cppreference.com/w/cpp/filesystem/directory_iterator

- 137
- 2
- 7
-
To confirm, is `is_regular_file()` your custom function or an in-built C++ one? Because I'm getting an error for that: `error: ‘const class std::experimental::filesystem::v1::__cxx11::directory_entry’ has no member named ‘is_regular_file’ if (entry.is_regular_file()) { ^~~~~~~~~~~~~~~` – Milan Oct 03 '22 at 14:20
-
1@Milan : `entry.is_regular_file()` should be `is_regular_file(entry.path())` which is a `std:filesystem` function. – AndyK Feb 05 '23 at 18:34
If they are well named, sorted, and have the same extension, you could simply do count them with standard C++ library.
Assume the file names are like "img_0.jpg..img_10000.jpg..img_n.jpg", Just check if they are in the folder or not.
int Trainer::fileCounter(string dir, string prefix, string extension)
{
int returnedCount = 0;
int possibleMax = 5000000; //some number you can expect.
for (int istarter = 0; istarter < possibleMax; istarter++){
string fileName = "";
fileName.append(dir);
fileName.append(prefix);
fileName.append(to_string(istarter));
fileName.append(extension);
bool status = FileExistenceCheck(fileName);
returnedCount = istarter;
if (!status)
break;
}
return returnedCount;
}
bool Trainer::FileExistenceCheck(const std::string& name) {
struct stat buffer;
return (stat(name.c_str(), &buffer) == 0);
}

- 579
- 1
- 5
- 16
You would need to use a native API or framework.