Skip to content

Instantly share code, notes, and snippets.

@klmr
Last active April 7, 2021 20:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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