Is it possible in c++ to count the number of files with a given extension in a directory?
I'm writing a program where it would be nice to do something like this (pseudo-code):
if (file_extension == ".foo")
num_files++;
for (int i = 0; i < num_files; i++)
// do something
Obviously, this program is much more complex, but this should give you the general idea of what I'm trying to do.
If this is not possible, just tell me.
Thanks!
First of all what OS are you writing for?
FindFirstFile
andFindNextFile
in MSDN.man
foropendir
andreaddir
orreaddir_r
.This kind of functionality is OS-specific, therefore there is no standard, portable method of doing this.
However, using Boost's Filesystem library you can do this, and much more file system related operations in a portable manner.
There is nothing in the C or C++ standards themselves about directory handling but just about any OS worth its salt will have such a beast, one example being the
findfirst/findnext
functions orreaddir
.The way you would do it is a simple loop over those functions, checking the end of the strings returned for the extension you want.
Something like:
As stated, the actual functions you will use for traversing the directory are OS-specific.
For UNIX, it would almost certainly be the use of opendir, readdir and closedir. This code is a good starting point for that: