...

/

Demo Example for Path Object

Demo Example for Path Object

This lesson shows a demo code sample that we are going to discuss in the upcoming lessons. The code basically displays files in a given directory.

We'll cover the following...

Demo

Instead of exploring the library piece by piece at the start, let’s see a demo example: displaying basic information about all the files in a given directory (recursively). This should give you a high-level overview of how the library looks like.

Press + to interact
#include <filesystem>
#include <iomanip>
#include <iostream>
namespace fs = std::filesystem;
void DisplayDirectoryTree(const fs::path& pathToScan, int level = 0) {
for (const auto& entry : fs::directory_iterator(pathToScan)) {
const auto filenameStr = entry.path().filename().string();
if (entry.is_directory()) {
std::cout << std::setw(level * 3) << "" << filenameStr << '\n';
DisplayDirectoryTree(entry, level + 1);
}
else if (entry.is_regular_file()) {
std::cout << std::setw(level * 3) << ""<< filenameStr
<< ", size " << fs::file_size(entry) << " bytes\n";
}
else
std::cout << std::setw(level * 3) << "" << " [?]" << filenameStr << '\n';
}
}
int main(int argc, char* argv[]) {
try {
const fs::path pathToShow{ argc >= 2 ? argv[1] : fs::current_path() };
std::cout << "listing files in the directory: "
<< fs::absolute(pathToShow).string() << '\n';
DisplayDirectoryTree(pathToShow);
}
catch (const fs::filesystem_error& err) {
std::cerr << "filesystem error! " << err.what() << '\n';
}
catch (const std::exception& ex) {
std::cerr << "general exception: " << ex.what() << '\n';
}
}

Sample Outputs

We can run this program on a temp path D:\testlist and see the following output:

Running on Windows:

.\ListFiles.exe D:\testlist\
listing files in the directory: D:\testlist\
abc.txt, size 357 bytes
def.txt, size 430 bytes
ghi.txt, size 190 bytes
dirTemp
   jkl.txt, size 162 bytes
   mno.txt,
...