← Documentation
ADS-IDAC Engine 5.0.0
CheckedIO.h
Go to the documentation of this file.
1#pragma once
2
3#include <fstream>
4#include <iostream>
5#include <string>
6#include <vector>
7#include <cstdlib>
8
19inline bool checked_close(std::ofstream& ofs, const std::string& path) {
20 ofs.flush();
21 const bool ok = ofs.good();
22 ofs.close();
23 if (!ok) {
24 std::cerr << "ERROR: write failed (disk full or I/O error): " << path << std::endl;
25 std::ofstream ferr("err messages.txt", std::ios::app);
26 ferr << "ERROR: write failed (disk full or I/O error): " << path << "\n";
27 }
28 return ok;
29}
30
42inline void write_file_or_die(const std::string& path, const char* data, size_t size) {
43 std::ofstream ofs(path, std::ios::binary);
44 if (ofs) {
45 ofs.write(data, static_cast<std::streamsize>(size));
46 ofs.flush();
47 }
48 if (!ofs.good()) {
49 std::cerr << "FATAL: failed to write " << size << " bytes to " << path
50 << " (disk full?) — restart data would be corrupt." << std::endl;
51 std::exit(1);
52 }
53 ofs.close();
54}
55
64inline bool read_file_verified(const std::string& path, std::vector<char>& out) {
65 std::ifstream ifs(path, std::ios::binary | std::ios::ate);
66 if (!ifs) {
67 std::cerr << "ERROR: cannot open " << path << std::endl;
68 return false;
69 }
70 const auto sz = static_cast<std::streamsize>(ifs.tellg());
71 ifs.seekg(0);
72 out.resize(static_cast<size_t>(sz));
73 ifs.read(out.data(), sz);
74 if (ifs.gcount() != sz) {
75 std::cerr << "ERROR: short read from " << path << " (" << ifs.gcount()
76 << " of " << sz << " bytes)" << std::endl;
77 return false;
78 }
79 return true;
80}
void write_file_or_die(const std::string &path, const char *data, size_t size)
Write an entire buffer to a binary file (truncating it); fatal on any failure.
Definition: CheckedIO.h:42
bool checked_close(std::ofstream &ofs, const std::string &path)
Flush and close an output stream and report a failed write.
Definition: CheckedIO.h:19
bool read_file_verified(const std::string &path, std::vector< char > &out)
Read an entire binary file into out, verifying the byte count.
Definition: CheckedIO.h:64
int size
Total number of MPI processes.