Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //#include <libdj/istream.h>
- #include <istream>
- #include <stdexcept>
- namespace dj {
- inline
- void read_istream_into_string(std::istream& inp, std::string &outp) {
- // Requires inp.seekg(), and inp.tellg()
- if (!inp.good()) {
- throw std::invalid_argument("read_istream_into_string: istream argument 'inp.good()' returned false.");
- }
- if (!inp.seekg(0, std::ios::end)) {
- throw std::runtime_error("read_istream_into_string: istream inp.seekg(0 std::ios::end) failed");
- }
- outp.reserve(inp.tellg()); // Throws bad_alloc and length_error
- if (!inp.seekg(0, std::ios::beg)) {
- throw std::runtime_error("read_istream_into_string: istream inp.seekg(0, std::ios::beg) failed");
- }
- outp.assign((std::istreambuf_iterator<char>(inp)),
- std::istreambuf_iterator<char>());
- }
- }
- #include <fstream>
- int main() {
- std::ifstream inp("junk.txt");
- std::string buffer;
- dj::read_istream_into_string(inp, buffer);
- std::cout << buffer << std::endl;
- }
Add Comment
Please, Sign In to add comment