Guest User

Untitled

a guest
Feb 23rd, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. //#include <libdj/istream.h>
  2. #include <istream>
  3. #include <stdexcept>
  4.  
  5. namespace dj {
  6. inline
  7. void read_istream_into_string(std::istream& inp, std::string &outp) {
  8. // Requires inp.seekg(), and inp.tellg()
  9. if (!inp.good()) {
  10. throw std::invalid_argument("read_istream_into_string: istream argument 'inp.good()' returned false.");
  11. }
  12. if (!inp.seekg(0, std::ios::end)) {
  13. throw std::runtime_error("read_istream_into_string: istream inp.seekg(0 std::ios::end) failed");
  14. }
  15. outp.reserve(inp.tellg()); // Throws bad_alloc and length_error
  16. if (!inp.seekg(0, std::ios::beg)) {
  17. throw std::runtime_error("read_istream_into_string: istream inp.seekg(0, std::ios::beg) failed");
  18. }
  19. outp.assign((std::istreambuf_iterator<char>(inp)),
  20. std::istreambuf_iterator<char>());
  21. }
  22. }
  23.  
  24. #include <fstream>
  25.  
  26. int main() {
  27. std::ifstream inp("junk.txt");
  28. std::string buffer;
  29. dj::read_istream_into_string(inp, buffer);
  30. std::cout << buffer << std::endl;
  31. }
Add Comment
Please, Sign In to add comment