C++ std::filesystem::create_directories
Create a nested directory tree and verify the final directory.
A simple example
std::filesystem::create_directories
- Start with An empty practice folder
- Do this Create a/b including parents
- Result Both directories exist
Syntax
fs::create_directories(week)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 on macOS or Linux with a POSIX shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonPrepare nested hand-in folders
A department creates a hand-in folder for each class and week. The job runs again if the first delivery is interrupted, so existing directories should remain usable on a second run.
#include <unistd.h>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <stdexcept>
namespace fs = std::filesystem;
int main() {
char pattern[] = "/tmp/file-lesson-XXXXXX";
if (!mkdtemp(pattern)) throw std::runtime_error("Cannot create workspace");
fs::path base(pattern);
try {
auto week = base / "class" / "week1";
fs::create_directories(week);
fs::create_directories(week);
if (fs::is_directory(week)) std::cout << "ready\n";
} catch (...) {
fs::remove_all(base);
throw;
}
fs::remove_all(base);
}
ready
The second attempt finds the same directory and the application can use it.
Locate a rehearsal score
The choir stores each score inside a season folder. Create the named season or class folder and its proofs subfolder in an empty workspace. What state should the operator see after successful creation?
Locate a workshop handout
An instructor stores the current template in a class folder. Create the named season or class folder and its proofs subfolder in an empty workspace. What state should the operator see after successful creation?
What to watch for
Handle a regular file occupying any required directory name as an error.