Galaxis Codebase  1.0.0
Team Galaxis software stack for the Carolo Cup 2023 - ROS2 based software
file.cpp
Go to the documentation of this file.
1 #include "utils/file.hpp"
2 
3 using namespace std;
4 
5 shared_ptr<vector<string>> galaxis::utils::read_from_file_to_string(string const& p_filepath) {
6  shared_ptr<vector<string>> contentUPtr = std::make_shared<vector<string>>();
7 
8  ifstream file;
9  file.open(p_filepath);
10 
11  if(file.is_open()) {
12 
13  string line;
14  while(getline(file, line)) {
15  if(!line.empty()) {
16  contentUPtr->push_back(line);
17  }
18  }
19 
20  } else {
21  log_error("Failed to open file.");
22  }
23 
24  file.close();
25 
26  return move(contentUPtr);
27 }
28 
29 shared_ptr<vector<float>> galaxis::utils::read_from_file_to_float(string const& p_filepath) {
30  auto contentStringSPtr = galaxis::utils::read_from_file_to_string(p_filepath);
31 
32  shared_ptr<vector<float>> contentUPtr = std::make_shared<vector<float>>();
33 
34  for(auto& c: *contentStringSPtr) {
35  contentUPtr->push_back(stof(c));
36  }
37 
38  return move(contentUPtr);
39 }
40 
41 shared_ptr<std::map<std::string, std::string>> galaxis::utils::read_configuration(string const& p_filepath) {
42  shared_ptr<std::map<std::string, std::string>> contentSPtr = std::make_shared<std::map<std::string, std::string>>();
43 
44  ifstream file;
45  file.open(p_filepath);
46 
47  if(file.is_open()) {
48 
49  string line;
50  while(getline(file, line)) {
51  if(!line.empty()) {
52 
53  size_t lineDelimiterPosition = line.find("=");
54  if (lineDelimiterPosition == std::string::npos || lineDelimiterPosition == 0) continue; // continue if line not in format: key=value
55 
56  std::string key = line.substr(0, lineDelimiterPosition);
57  std::string value = line.substr(lineDelimiterPosition + 1, line.size());
58 
59  if (contentSPtr->find(key) == contentSPtr->end())
60  contentSPtr->insert(std::pair<std::string, std::string>(key, value));
61  else
62  log_warning("[File] Duplicated Keys while loading config file: ", p_filepath);
63 
64  }
65  }
66 
67  } else {
68  log_warning("Failed to open file.");
69  throw std::runtime_error("Failed to open file.");
70  }
71 
72  file.close();
73 
74  return contentSPtr;
75 }
galaxis::utils::log_error
void log_error(const Args &... args)
Definition: logger.hpp:50
galaxis::utils::log_warning
void log_warning(const Args &... args)
Definition: logger.hpp:41
file.hpp
galaxis::utils::read_configuration
shared_ptr< std::map< std::string, std::string > > read_configuration(string const &p_filepath)
Definition: file.cpp:41
galaxis::utils::read_from_file_to_float
shared_ptr< vector< float > > read_from_file_to_float(string const &p_filepath)
Definition: file.cpp:29
galaxis::utils::read_from_file_to_string
shared_ptr< vector< string > > read_from_file_to_string(string const &p_filepath)
Definition: file.cpp:5