Did I cover all the bases? Can this be improved (best practice)?
Edit... I've come up with some improvements. When I tried edit the code, the software complained about too much code and too little blather (paraphrasing). So, here I am blathering. When I have blathered enough, the code below will be the new stuff.
//#include <libdj/istream.h>
#include <istream>
#include <string>
#include <stdexcept>
namespace dj {
inline
void append_istream_onto_string(std::istream& inp, std::string &outp) {
// Uses inp.seekg(), and inp.tellg() to determine size
// Throws (std::) invalid_argument, runtime_error, bad_alloc, length_error
if (!inp.good()) {
throw std::invalid_argument
("Input stream is not valid. (read_istream_into_string)");
}
if (!inp.seekg(0, std::ios::end)) {
throw std::runtime_error
("Cannot deduce length of input stream. (read_istream_into_string)");
}
outp.reserve(outp.size() + inp.tellg()); // Throws bad_alloc and length_error
if (!inp.seekg(0, std::ios::beg)) {
throw std::runtime_error
("Input stream seek failed. (read_istream_into_string)");
}
outp.append((std::istreambuf_iterator<char>(inp)),
std::istreambuf_iterator<char>());
}
inline
std::string to_string(std::istream& inp) {
std::string ret;
append_istream_onto_string(inp, ret);
return ret;
}
}
#include <fstream>
int main() {
std::ifstream inp("junk.txt");
std::string buffer;
buffer = "// junk.txt\n";
try {
//dj::append_istream_onto_string(inp, buffer);
buffer = dj::to_string(inp);
} catch (const std::exception &ex) {
std::cout << ex.what() << std::endl;
}
std::cout << buffer << std::endl;
}