Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append binary file with a binary file in C++

I have two binary files and I would like to append one with the other. How can I do it?

std::ofstream outFile;
outFile.open( "file.bin", ? );

what should be the nest line?

like image 661
user1016179 Avatar asked Jun 10 '26 06:06

user1016179


1 Answers

There's a one liner for this:

std::ofstream outFile("file.out", std::ios::ate );
std::ifstream inFile( "file.in" );

std::copy( 
    (std::istreambuf_iterator<char>(inFile)),  // (*)
     std::istreambuf_iterator<char>(),
     std::ostreambuf_iterator<char>(outFile)
);

(*) Extra pair of parentheses to prevent parsing this as function declaration.

For better performance you could read the file in chunks, using ifstream::read and write them with ofstream::write.

like image 88
jrok Avatar answered Jun 11 '26 21:06

jrok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!