From 2e23f6368d354da819f98a8c282d234e023fe961 Mon Sep 17 00:00:00 2001 From: Giovanni La Mura <giovanni.lamura@inaf.it> Date: Thu, 19 Oct 2023 12:19:55 +0200 Subject: [PATCH] Create a module for parsing functions --- src/Parsers.cpp | 26 ++++++++++++++++++++++++++ src/include/Parsers.h | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 src/Parsers.cpp create mode 100644 src/include/Parsers.h diff --git a/src/Parsers.cpp b/src/Parsers.cpp new file mode 100644 index 00000000..321c91df --- /dev/null +++ b/src/Parsers.cpp @@ -0,0 +1,26 @@ +/*! \file Parsers.cpp + */ + +#include <fstream> +#include <string> +#include "include/List.h" +#include "include/Parsers.h" + +std::string *load_file(std::string file_name, int *count = 0) { + std::fstream input_file(file_name.c_str(), std::ios::in); + List<std::string> file_lines = List<std::string>(); + std::string line; + if (input_file.is_open()) { + getline(input_file, line); + file_lines.set(0, line); + while (getline(input_file, line)) { + file_lines.append(line); + } + input_file.close(); + } else { + throw FILE_NOT_FOUND_ERROR; + } + std::string *array_lines = file_lines.to_array(); + if (count != 0) *count = file_lines.length(); + return array_lines; +} diff --git a/src/include/Parsers.h b/src/include/Parsers.h new file mode 100644 index 00000000..a4523de6 --- /dev/null +++ b/src/include/Parsers.h @@ -0,0 +1,34 @@ +/*! \file Parsers.h + */ + +#ifndef INCLUDE_PARSERS_H_ +#define INCLUDE_PARSERS_H_ + +#ifndef FILE_NOT_FOUND_ERROR +//! Error code if a file is not found. +#define FILE_NOT_FOUND_ERROR 21 +#endif + +/*! \brief Load a text file as a sequence of strings in memory. + * + * The configuration of the field expansion code in FORTRAN uses + * shared memory access and file I/O operations managed by different + * functions. Although this approach could be theoretically replicated, + * it is more convenient to handle input and output to distinct files + * using specific functions. load_file() helps in the task of handling + * input such as configuration files or text data structures that need + * to be loaded entirely. The function performs a line-by line scan of + * the input file and returns an array of strings that can be later + * parsed and ingested by the concerned code blocks. An optional pointer + * to integer allows the function to keep track of the number of file + * lines that were read, if needed. + * + * \param file_name: `string` The path of the file to be read. + * \param count: `int*` Pointer to an integer recording the number of + * read lines [OPTIONAL, default=NULL]. + * \return array_lines `string*` An array of strings, one for each input + * file line. + */ +std::string *load_file(std::string file_name, int *count); + +#endif /* INCLUDE_PARSERS_H_ */ -- GitLab