C++ std::filesystem::exists
Use a filesystem status query to decide whether a receipt is available for a reprint preview.
A simple example
std::filesystem::exists
- Start with No file named a.txt
- Do this Open a.txt for reading
- Result File missing
Syntax
std::filesystem::exists(receipt)
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
./lessonOpen the first receipt of the day
A new checkout starts with an empty receipt folder. When the cashier asks to reprint today's first receipt, the app should explain that a receipt has yet to be saved.
#include <iostream>
#include <filesystem>
#include <stdlib.h>
#include <unistd.h>
int main() {
char folder[] = "/tmp/checkout-XXXXXX";
if (!mkdtemp(folder)) return 1;
std::filesystem::path desk(folder);
bool available = std::filesystem::exists(desk / "today.txt");
std::filesystem::remove(desk);
if (!available) std::cout << "No receipt yet\n";
return 0;
}
No receipt yet
The program owns a fresh, empty directory, so in this run the named receipt is known to be absent.
Read a saved shift record
The closing clerk saved the file before leaving. Open the expected file and show the desk whether it is available.
Handle an unsubmitted handover
The next shift opens an empty inbox before the first clerk submits a file. Open the expected file and show the desk whether it is available.
What to watch for
A status snapshot can become stale. Handle failure again when the real application opens the receipt. This example uses POSIX mkdtemp on macOS or Linux.