C++ std::filesystem::space
Inspect the capacity of the volume containing a directory.
A simple example
std::filesystem::space
- Start with Example volume with 10 units total and 4 available
- Do this Compare a 3-unit request with available space
- Result It fits
Syntax
fs::space(base)
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
./lessonCheck room for a class recording
A teacher wants to record a lesson on a chosen local volume. Query capacity for the directory that will hold the recording so a large system drive cannot mask a nearly full destination.
#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 disk = fs::space(base);
if (disk.capacity > 0 && disk.capacity != static_cast<std::uintmax_t>(-1))
std::cout << "measured\n";
} catch (...) {
fs::remove_all(base);
throw;
}
fs::remove_all(base);
}
measured
The queried volume reports a positive total capacity.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. On a drive with room to spare, compare its available byte count with the size of one extra copy. Can this copy fit?
Prepare a studio handover
A stage manager saves a two-word instruction for the next shift. On a drive with room to spare, compare its available byte count with the size of one extra copy. Can this copy fit?
What to watch for
Space figures can change while the application runs and may be limited by account quotas.