Files counting

Hello, i'm a beginner in c++ programming and i need your help. I have a problem where i must count the files with .txt extension from a specified folder.
Thank you for your time.
You'll need to use something specific to your operating system or an external library. Nothing in STD C++ will do this.

I recommend the boost::filesystem library as it can be used in any operating system.

Once installed, you can do that with this function:
1
2
3
4
5
6
7
8
9
10
11
12
13
int count_files(std::string directory, std::string ext)
{
	namespace fs = boost::filesystem;
	fs::path Path(directory);
	int Nb_ext = 0;
	fs::directory_iterator end_iter; // Default constructor for an iterator is the end iterator

	for (fs::directory_iterator iter(Path); iter != end_iter; ++iter)
		if (iter->path().extension() == ext)
			++Nb_ext;

	return Nb_ext;
}


And this is how I'd use it:
1
2
3
4
5
6
7
8
9
10
11
12
#include <boost/filesystem.hpp>
#include <string>
#include <iostream>

int count_files(std::string, std::string);

int main()
{
	std::cout << count_files("c://temp",".cpp") << std::endl;
	std::cout << count_files("c://windows//System32",".dll") << std::endl;
	return 0;
}
3
2442


You can get boost from here:
http://sourceforge.net/projects/boost/files/boost/1.49.0/
or from here
http://www.boost.org/users/download/
Last edited on
closed account (4z0M4iN6)
You can do this:

You wite a c++ program, maybe LookupCount.exe
The Program should look at the second last entry of a temporary file, where it will find the count. This count the program should return (or print it also).

Then you write the following lines in a batch file (.cmd or .bat)

@echo off
dir file.txt > temp.txt
LookupCount .exe temp.txt
echo Count: %errorlevel%
del temp.txt




Thank you. It worked.
Topic archived. No new replies allowed.