1717#include " fmt/format.h"
1818#include " umpire/event/event_json.hpp"
1919#include " umpire/json/json.hpp"
20+ #include " umpire/util/Macros.hpp"
2021#include " umpire/util/error.hpp"
2122
2223namespace umpire {
@@ -25,11 +26,26 @@ namespace event {
2526json_file_store::json_file_store (const std::string& filename, bool read_only)
2627 : m_filename{filename}, m_read_only{read_only}
2728{
29+ m_fstream = fopen (m_filename.c_str (), m_read_only ? " r" : " w" );
30+
31+ if (m_fstream == NULL ) {
32+ UMPIRE_ERROR (umpire::runtime_error, fmt::format (" Failed to open {}" , m_filename));
33+ }
34+ }
35+
36+ json_file_store::~json_file_store ()
37+ {
38+ if (m_fstream != nullptr ) {
39+ if (!m_read_only) {
40+ fflush (m_fstream); // Flush buffered writes before close.
41+ }
42+ fclose (m_fstream); // Close the file
43+ m_fstream = nullptr ;
44+ }
2845}
2946
3047void json_file_store::insert (const event& e)
3148{
32- open_store ();
3349 nlohmann::json json_event = e;
3450 std::stringstream ss;
3551 ss << json_event;
@@ -112,7 +128,6 @@ std::vector<event> json_file_store::get_events()
112128 std::vector<event> events;
113129 std::size_t line_number{1 };
114130
115- open_store ();
116131 while (getline (&line, &len, m_fstream) != -1 ) {
117132 nlohmann::json json_event;
118133 event e;
@@ -166,17 +181,5 @@ std::vector<event> json_file_store::get_events()
166181 return events;
167182}
168183#endif
169-
170- void json_file_store::open_store ()
171- {
172- if (m_fstream == NULL ) {
173- m_fstream = fopen (m_filename.c_str (), m_read_only ? " r" : " w" );
174-
175- if (m_fstream == NULL ) {
176- UMPIRE_ERROR (umpire::runtime_error, fmt::format (" Failed to open {}" , m_filename));
177- }
178- }
179- }
180-
181184} // namespace event
182185} // namespace umpire
0 commit comments