There's a neat trick that can be used to copy file contents in C++. If we have an std::ifstream input; for one file and an std::ofstream output; for a second file, the contents of input can be copied to output like this:
output << input.rdbuf();
This solution copies the entirety of the first file (or at least the entirety of the input stream that hasn't been consumed yet). My question is, how can I copy only a prefix (n first bytes) of an input stream to an output stream?
After looking through a bit of documentation, my idea was to somehow shorten the stream of the input and then copy it to the output stream:
input.rdbuf()->pubsetbuf(input.rdbuf()->eback(), length_to_output);
output << input.rdbuf();
The problem is, that this won't compile as eback is not public. This is only supposed to illustrate my idea. I know that I could just copy the entire input into a string and then copy a substring of it into the output, but I am worried that it will be less time- and memory-efficient. As such, I thought about using streams instead, like above.