Skip to content

Instantly share code, notes, and snippets.

@klmr
Last active May 20, 2024 21:23
Show Gist options
  • Save klmr/849cbb0c6e872dff0fdcc54787a66103 to your computer and use it in GitHub Desktop.
Save klmr/849cbb0c6e872dff0fdcc54787a66103 to your computer and use it in GitHub Desktop.
“Canonical” code to slurp a file in C++17
auto read_file(std::string_view path) -> std::string {
constexpr auto read_size = std::size_t{4096};
auto stream = std::ifstream{path.data()};
stream.exceptions(std::ios_base::badbit);
auto out = std::string{};
auto buf = std::string(read_size, '\0');
while (stream.read(& buf[0], read_size)) {
out.append(buf, 0, stream.gcount());
}
out.append(buf, 0, stream.gcount());
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment