Last active
January 15, 2025 01:29
-
-
Save klmr/849cbb0c6e872dff0fdcc54787a66103 to your computer and use it in GitHub Desktop.
“Canonical” code to slurp a file in C++17
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Should this include
out.reserve(std::filesystem::file_size(path));
or some other computation of file size based onstream
?