Reply to comment

Copying a File in C++, The Easy Way

Just a few days ago I spent way too long looking at the boost libraries to see if there was a way of adapting a std::fstream to an iterator type. I didn't find what I was looking for and did what I wanted a completely different way.

This morning while reading Stroustrup (The C++ Programming Language) I learned that what I was looking for was already built in to the standard library!

Well, after an hour or so of work I eliminated about 40 lines of code, made my code more maintainable and more readable.

As a test case, I put together this little example. The below code is a complete program, it will compile and run and copy "input.txt" to "output.txt".

It works with any file, binary or not (which is why the noskipws is needed). No, it is NOT the most efficient way of doing things, but it shows just how expressive the C++ standard library is.

#include <istream>
#include <iostream>
#include <fstream>
#include <iterator>
 
using namespace std;
 
int main()
{
  fstream f("input.txt", fstream::in|fstream::binary);
  f << noskipws;
  istream_iterator<unsigned char> begin(f);
  istream_iterator<unsigned char> end;
 
  fstream f2("output.txt",
    fstream::out|fstream::trunc|fstream::binary);
  ostream_iterator<char> begin2(f2);
 
  copy(begin, end, begin2);
}

Reply

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote>
  • Lines and paragraphs break automatically.
  • You may post PHP code. You should include <?php ?> tags.
  • Web page addresses and e-mail addresses turn into links automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <cpp>. The supported tag styles are: <foo>, [foo]. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • Images can be added to this post.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
1 + 11 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.