Counting/returning number of files in a folder?

Jun 13, 2018 at 6:07am
The only help I've found online so far to achieve this (storing the number of files in a given folder) is by using the Boost library. I'd rather not include anymore libraries to my current project if I don't have to.

So what other options to I have for figuring out how many files are within a folder, and storing that number in an integer data type?
Jun 13, 2018 at 7:09am
Jun 13, 2018 at 7:59am
@Thomas1965 I do have C++17 enabled in VS and included <experimental/filesystem> but can't seem to get PATH to be recognized, unless I'm just using it wrong

EDIT: Alright I've missed the experimental part being a namespace. So I've got
 
std::experimental::filesystem::path _dir;


so how would I now use this to look in a directory to count it's files?
Last edited on Jun 13, 2018 at 8:15am
Jun 13, 2018 at 12:38pm
Here's how to display all the files in the directory - using VS 2017.
Just implement the logic to count.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
#include <fstream>
#include <experimental/filesystem>

namespace fs = std::experimental::filesystem;

int main()
{
  fs::path path("C:\\Temp");
  for (auto& p : fs::directory_iterator(path))
    std::cout << p << '\n';
  
}
Jun 13, 2018 at 2:42pm
you can ask the OS via 'system' calls using ls or dir (unix, windows) redirected to a file.
its not as clean as using OS specific libraries, but its one way to do it. Dir's final line gives the number of files summary so you can find that line and echo it.

Topic archived. No new replies allowed.