29inline std::vector<uint8_t>
read_file(
const std::string& filename,
size_t bytes = 0)
34 constexpr size_t CHUNK = 65536;
35 auto read_chunked = [](
int fd,
const std::string& name) {
36 std::vector<uint8_t> result;
41 result.resize(total + CHUNK);
42 n =
::read(fd, result.data() + total, CHUNK);
46 total +=
static_cast<size_t>(n);
50 THROW std::runtime_error(
"Failed to read from " + name +
": " + strerror(errno));
56 if (filename ==
"-") {
57 return read_chunked(STDIN_FILENO,
"stdin");
64 auto raw_size = std::filesystem::file_size(filename, ec);
67 int fd = open(filename.c_str(), O_RDONLY);
69 THROW std::runtime_error(
"Unable to open file: " + filename +
" (" + strerror(errno) +
")");
72 std::vector<uint8_t> fileData;
73 if (!file_size.has_value()) {
75 fileData = read_chunked(fd, filename);
79 size_t to_read = bytes == 0 ? *file_size : bytes;
80 fileData.resize(to_read);
82 while (total < to_read) {
83 ssize_t got =
::read(fd, fileData.data() + total, to_read - total);
86 THROW std::runtime_error(
"Failed to read file: " + filename +
" (" + strerror(errno) +
")");
91 total +=
static_cast<size_t>(got);
93 fileData.resize(total);