Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

std::filesystem

Use case

Binary file operations.

Explanation

std::filesystem provides portable file system operations (paths, queries, directory iteration etc.).

Code

#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

int main() {
  fs::path app = "/Applications/Firefox.app/Contents/MacOS/firefox";

  if (fs::exists(app)) {
    std::cout << "Binary: " << app.filename() << "\n";
    std::cout << "Size: " << fs::file_size(app) << " bytes.\n";
  }

  fs::path frameworks = "/System/Library/Frameworks";
  int count = 0;
  for (const auto &entry : fs::directory_iterator(frameworks)) {
    if (entry.path().extension() == ".framework") {
      std::cout << entry.path().filename() << "\n";
      ++count;
      if (count == 3) {
        break;
      }
    }
  }

  return 0;
}

View on GitHub.

Output

$ ./src/c++17/build/std-filesystem
Binary: "firefox"
Size: 174304 bytes.
"WiFiAware.framework"
"JavaRuntimeSupport.framework"
"MetricKit.framework"