From 30c35717da7dfb5cd6bc4a9f9fe57b2d89eb3bfd Mon Sep 17 00:00:00 2001 From: Emilio <Emilio.Meschi@cern.ch> Date: Mon, 24 Oct 2022 00:59:43 +0200 Subject: [PATCH] class to delegate file output file actions --- src/OutputFileHandler.cc | 57 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/OutputFileHandler.cc diff --git a/src/OutputFileHandler.cc b/src/OutputFileHandler.cc new file mode 100644 index 00000000..9afd8e39 --- /dev/null +++ b/src/OutputFileHandler.cc @@ -0,0 +1,57 @@ +#include "OutputFileHandler.h" + +#include "log.h" + +void OutputFileHandler::create_output_directory_maybe(std::string &output_directory) { + struct stat sb; + + /* check if path exists and is a directory */ + if (stat(output_directory.c_str(), &sb) == 0) { + if (S_ISDIR(sb.st_mode)) { // output directory already exists + return; + } + std::string err = "ERROR The output directory path '" + output_directory + + "' exists, but the path is not a directory!"; + LOG(ERROR) << err; + throw std::runtime_error(err); + } + + if (!tools::filesystem::create_directories(output_directory)) { + std::string err = + tools::strerror("ERROR when creating the output directory '" + output_directory + "'"); + LOG(ERROR) << err; + throw std::runtime_error(err); + } + LOG(TRACE) << "Created output directory: " << output_directory << "'."; +} + +void OutputFileHandler::open_file(uint32_t index, uint32_t run) { + // Create a new file + create_output_directory_maybe(working_files_basepath_); + std::string current_filename_a = + output_directory + "/" + + format_run_file_stem(my_output_filename_prefix, current_run_number, index_); + std::string filename = + output_directory + "/" + + format_run_file_stem(my_output_filename_prefix, control.run_number, index_); + LOG(INFO) << "opening file with index " << index_; + outFile.setFile(fopen(filename.c_str(), "w")); + outFile.setIndex(index_); + if (outFile.getFile() == NULL) { + std::string err = tools::strerror("ERROR when creating file '" + current_filename_a + "'"); + LOG(ERROR) << err; + throw std::runtime_error(err); + } +} + +/* + * Create a properly formatted file name + * TODO: Change to C++ + */ +std::string OutputFileHandler::format_filename(std::string &path, uint32_t run_number, + uint32_t index) { + char run_order_stem[PATH_MAX]; + snprintf(run_order_stem, sizeof(run_order_stem), "%s_%06d_%06d.dat", filename_prefix.c_str(), + run_number, file_count); + return std::string(run_order_stem); +} -- GitLab