|
| 1 | +// Copyright 2023 Proyectos y Sistemas de Mantenimiento SL (eProsima). |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +/** |
| 16 | + * @file file_utils.cpp |
| 17 | + */ |
| 18 | + |
| 19 | +#include <iostream> // TODO remove |
| 20 | +#include <fstream> |
| 21 | + |
| 22 | +#include <cpp_utils/exception/PreconditionNotMet.hpp> |
| 23 | +#include <cpp_utils/file/file_utils.hpp> |
| 24 | +#include <cpp_utils/utils.hpp> |
| 25 | + |
| 26 | +namespace eprosima { |
| 27 | +namespace utils { |
| 28 | + |
| 29 | +std::string file_to_string( |
| 30 | + const char* file_name, |
| 31 | + bool strip_chars /* = true */) |
| 32 | +{ |
| 33 | + auto strings = file_to_strings(file_name, strip_chars, false); |
| 34 | + std::string result; |
| 35 | + |
| 36 | + for (const auto& st : strings) |
| 37 | + { |
| 38 | + result += st + "\n"; |
| 39 | + } |
| 40 | + |
| 41 | + return result; |
| 42 | +} |
| 43 | + |
| 44 | +std::vector<std::string> file_to_strings( |
| 45 | + const char* file_name, |
| 46 | + bool strip_chars /* = true */, |
| 47 | + bool strip_empty_lines /* = false */) |
| 48 | +{ |
| 49 | + std::string new_line; |
| 50 | + std::vector<std::string> result; |
| 51 | + |
| 52 | + // Open file |
| 53 | + std::ifstream file(file_name); |
| 54 | + |
| 55 | + if (!file.is_open()) |
| 56 | + { |
| 57 | + throw PreconditionNotMet( |
| 58 | + STR_ENTRY << "File <" << file_name << "> could not be read."); |
| 59 | + } |
| 60 | + |
| 61 | + while (getline(file, new_line)) |
| 62 | + { |
| 63 | + if (strip_chars) |
| 64 | + { |
| 65 | + strip_str(new_line); |
| 66 | + } |
| 67 | + |
| 68 | + if (!(strip_empty_lines && new_line.empty())) |
| 69 | + { |
| 70 | + result.push_back(new_line); |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + return result; |
| 75 | +} |
| 76 | + |
| 77 | +} /* namespace utils */ |
| 78 | +} /* namespace eprosima */ |
0 commit comments