简体   繁体   中英

Copy only part of a binary file in C++

This is a nice and intuitive way to copy files:

#include <fstream>

int main()
{
    std::ifstream  src("from.bn", std::ios::binary);
    std::ofstream  dst("to.bn",   std::ios::binary);

    dst << src.rdbuf();
}

How can one modify it in order to just copy the first n bytes of src ?

For the first n characters , you can use:

std::copy_n(std::istreambuf_iterator<char>(src), n, std::ostreambuf_iterator<char>(dst));

If you're not sure that their will be 'enough' data in the input stream, you can use readsome() to get what's there, up to a given limit (if you know there will be a big enough input stream, just use read ):

#include <fstream>

int main()
{
    constexpr size_t amount = 4242;
    char data[amount];
    std::ifstream  src("from.bn", std::ios::binary);
    std::ofstream  dst("to.bn", std::ios::binary);

    size_t actual = src.readsome(data, amount);
    dst.write(data, actual);

    return 0;
}

You can use the .read() method of std::ifstream, which enables you to read N bytes of data.
To be fully changeable, you can add a call to .seekg() , to move into the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM