C++ std::filesystem::remove
Remove an existing file and check that its name is gone.
A simple example
std::filesystem::remove
- Start with A practice file exists
- Do this Delete that file
- Result The path is absent
Syntax
fs::remove(preview)
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
./lessonClear a disposable print preview
A library kiosk creates a preview whenever a borrower asks for a printout. After printing, the kiosk must remove that scratch file and confirm that the job has finished cleaning up.
#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 preview = base / "preview";
std::ofstream(preview) << "label";
if (fs::remove(preview) && !fs::exists(preview)) std::cout << "removed\n";
} catch (...) {
fs::remove_all(base);
throw;
}
fs::remove_all(base);
}
removed
The check runs after removal and confirms the preview path is absent.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. The desk removes the temporary note after handover. Does its original name still identify an entry?
Prepare a studio handover
A stage manager saves a two-word instruction for the next shift. The desk removes the temporary note after handover. Does its original name still identify an entry?
What to watch for
Deletion and missing-file behavior vary by API. Limit cleanup to paths created by this job.