argpar: sync with upstream
[babeltrace.git] / src / cpp-common / bt2c / file-utils.cpp
... / ...
CommitLineData
1
2/*
3 * Copyright (c) 2022 Francis Deslauriers <francis.deslauriers@efficios.com>
4 *
5 * SPDX-License-Identifier: MIT
6 */
7#include <fstream>
8
9#include "logging.hpp"
10
11#include "exc.hpp"
12#include "file-utils.hpp"
13
14namespace bt2c {
15
16std::vector<std::uint8_t> dataFromFile(const CStringView filePath, const Logger& logger,
17 const bool fatalError)
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 */
23 std::ifstream file {filePath.data(), std::ios::binary | std::ios::ate};
24
25 if (!file) {
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
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 */
This page took 0.023011 seconds and 5 git commands to generate.