std::optional read_file_prefix()

in xar/XarHelpers.cpp [15:36]


std::optional<std::string> read_file_prefix(
    const char* filename,
    size_t max_bytes) {
  int fd = open(filename, O_RDONLY | O_CLOEXEC);
  if (fd < 0) {
    return std::nullopt;
  }

  std::string buf;
  buf.resize(max_bytes);
  ssize_t res = read(fd, &buf[0], buf.size());
  if (res < 0) {
    return std::nullopt;
  }
  buf.resize(res);
  res = close(fd);
  if (res < 0) {
    return std::nullopt;
  }

  return buf;
}