Rise
The Vieneo Province
Loading...
Searching...
No Matches
OptionalDiagnosticFile.h
Go to the documentation of this file.
1#pragma once
2
3#include <cstdio>
4#include <fcntl.h>
5#include <io.h>
6#include <share.h>
7#include <sys/stat.h>
8
9// Optional physics diagnostics must never turn a failed file open into a
10// fatal CRT call. Each stream tries once and owns its descriptor privately.
12{
13public:
14 static constexpr unsigned BufferSize = 2048;
15
16 explicit OptionalDiagnosticFile(const char* path)
17 {
18 _sopen_s(&descriptor, path, _O_WRONLY | _O_CREAT | _O_TRUNC | _O_TEXT,
19 _SH_DENYWR, _S_IWRITE);
20 }
21
25
26 template<typename... Args>
27 bool Printf(const char* format, Args... args)
28 {
29 if (descriptor < 0) return false;
30 char buffer[BufferSize];
31 // snprintf truncates oversized diagnostics without invoking the
32 // secure CRT's fatal invalid-parameter handler.
33 const int count = std::snprintf(buffer, sizeof buffer, format, args...);
34 if (count < 0) return false;
35 const unsigned length = count < static_cast<int>(sizeof buffer)
36 ? static_cast<unsigned>(count) : sizeof buffer - 1;
37 if (_write(descriptor, buffer, length) == static_cast<int>(length)) return true;
38 Close(); // Stop optional logging after a write/disk error as well.
39 return false;
40 }
41
42private:
43 int descriptor = -1;
44 void Close()
45 {
46 if (descriptor >= 0) _close(descriptor);
47 descriptor = -1;
48 }
49};
OptionalDiagnosticFile(const char *path)
bool Printf(const char *format, Args... args)
static constexpr unsigned BufferSize
OptionalDiagnosticFile(const OptionalDiagnosticFile &)=delete
OptionalDiagnosticFile & operator=(const OptionalDiagnosticFile &)=delete