concatenating binary files

I

Igor R.

What's the laconic and standard way to do the subj - without an
explicit loop of [allocate-read-write]? In case of text files, I'd do
something like:
ifstream in("file1.txt", ios::in);
ofstream out("file2.txt", ios::eek:ut | ios::ate);
out << in.rdbuf();
But in case of binary files, I guess "<<" would do some undesired
formatting.
 
R

Ron AF Greve

Hi,


Igor R. said:
What's the laconic and standard way to do the subj - without an
explicit loop of [allocate-read-write]? In case of text files, I'd do
something like:
ifstream in("file1.txt", ios::in);
ofstream out("file2.txt", ios::eek:ut | ios::ate);
out << in.rdbuf();
But in case of binary files, I guess "<<" would do some undesired
formatting.

Open the files with ios_base::binary
and then use

char Buffer[ SomeSize ];

in.read( Buffer, sizeof( Buffer ) );
out.write( Buffer, in.gcount() );

In a loop.

Regards, Ron AF Greve

http://informationsuperhighway.eu/
 
S

sean_in_raleigh

What's the laconic and standard way to do the subj - without an
explicit loop of [allocate-read-write]?


If you're really committed to doing it without a
loop, then something like this will do it:

#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>

using namespace std;

void
append_file_to_stream(ofstream& out, const char *infile)
{
ifstream in(infile, ios_base::in | ios_base::binary);
in.exceptions(ios_base::badbit | ios_base::failbit);

istreambuf_iterator<char> in_it(in);
istreambuf_iterator<char> end;
ostreambuf_iterator<char> out_it(out);

copy(in_it, end, out_it);
}

int main()
{
ofstream out("outfile.bin", ios_base::eek:ut | ios_base::binary);
out.exceptions(ios_base::badbit | ios_base::failbit);

append_file_to_stream(out, "infile1.bin");
append_file_to_stream(out, "infile2.bin");
}


It's got a certain charm, but I've never really used this
kind of thing in real code, so YMMV.

Sean
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top