Commit | Line | Data |
---|---|---|
0b9614ad FD |
1 | |
2 | /* | |
3 | * Copyright (c) 2022 Francis Deslauriers <francis.deslauriers@efficios.com> | |
4 | * | |
5 | * SPDX-License-Identifier: MIT | |
6 | */ | |
7 | #include <fstream> | |
8 | ||
0f781e0b SM |
9 | #include "logging.hpp" |
10 | ||
0b9614ad FD |
11 | #include "exc.hpp" |
12 | #include "file-utils.hpp" | |
13 | ||
14 | namespace bt2c { | |
15 | ||
306722ab | 16 | std::vector<std::uint8_t> dataFromFile(const CStringView filePath, const Logger& logger, |
0f781e0b | 17 | const bool fatalError) |
0b9614ad FD |
18 | { |
19 | /* | |
20 | * Open a file stream and seek to the end of the stream to compute the size | |
21 | * of the buffer required. | |
22 | */ | |
306722ab | 23 | std::ifstream file {filePath.data(), std::ios::binary | std::ios::ate}; |
0b9614ad FD |
24 | |
25 | if (!file) { | |
0f781e0b SM |
26 | constexpr const char *msg = "No such file or directory: path=\"{}\""; |
27 | ||
28 | if (fatalError) { | |
29 | BT_CPPLOGE_APPEND_CAUSE_SPEC(logger, msg, filePath); | |
30 | } else { | |
31 | BT_CPPLOGD_SPEC(logger, msg, filePath); | |
32 | } | |
33 | ||
0b9614ad FD |
34 | throw NoSuchFileOrDirectoryError {}; |
35 | } | |
36 | ||
37 | const auto size = file.tellg(); | |
38 | std::vector<uint8_t> buffer(static_cast<std::size_t>(size)); | |
39 | ||
40 | /* | |
41 | * Seek the reading head back at the beginning of the stream to actually | |
42 | * read the content. | |
43 | */ | |
44 | file.seekg(0, std::ios::beg); | |
45 | file.read(reinterpret_cast<char *>(buffer.data()), size); | |
46 | return buffer; | |
47 | } | |
48 | ||
49 | } /* namespace bt2c */ |