C++ File Handling
Create a fresh private lab directory, write a report, check close and read it back before cleanup.
How it works
Streams own their open file resources, but a destructor cannot conveniently report a failed write to its caller. Check output state and an explicit close when successful storage matters. This lab creates its own directory and refuses to continue if that directory already exists, avoiding accidental replacement of a user report. It writes only inside that directory, verifies a line and removes only those owned paths. It is a single-process local fixture, not a secure shared-directory or crash-safe commit protocol.
Run it locally
Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.
c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror files.cpp -o lessonOn Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.
Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.
Example
#include <iostream>
#include <fstream>
#include <filesystem>
#include <string>
#include <system_error>
int main() {
namespace fs = std::filesystem;
const fs::path directory{"bhylu-cpp-file-lab"};
std::error_code error;
if (!fs::create_directory(directory, error) || error) { return 1; }
const auto path = directory / "manifest.txt";
std::ofstream output{path};
output << "Quay,12\n";
output.close();
if (!output) { fs::remove(path, error); fs::remove(directory, error); return 1; }
std::ifstream input{path};
std::string line;
bool valid = static_cast<bool>(std::getline(input, line)) && line == "Quay,12";
input.close();
fs::remove(path, error);
if (error || !fs::remove(directory, error) || error || !valid) { return 1; }
std::cout << "Manifest round trip verified\n";
}
Expected result
Manifest round trip verified
The path join uses filesystem::path rather than manual slash concatenation. The input comparison observes logical text after newline translation. For production persistence, consider permissions, collisions, atomic replacement and durability separately. RAII still closes streams on ordinary early exits, but this example explicitly checks the output close before declaring the report complete.
Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.