Search code examples
c++linuxiobinaryfilesbinary-data

C++ How To Copy Part of A Binary File To A New File?


I have a long binary file as an input to a function. I can copy all the data to a new file as follows:

void copyBinaryFile(string file){
    const char* fileChar = file.c_str(); 

    ifstream input(fileChar, ios::binary);
    ofstream output("/home/my_name/result.img", ios::binary);

    copy(istreambuf_iterator<char>(input),
    istreambuf_iterator<char>(),
    ostreambuf_iterator<char>(output)
    );
}

This works fine for copying an entire file in one go, however, what I actually want to do is take several non-consecutive chunks of the first binary file and write them all to the output file, i.e.

for(int i = 0; i < chunkArray.size(); i++){
    //copy 512 bytes from file1 to file2 starting at the chunkArray[i]th character
}

How would I do this? This is on Linux if it makes any difference.


Solution

    1. Use ifstream::seekg to move the reading position of the file.
    2. Read the appropriate number of bytes from the file.
    3. Process the data read from the file.
    4. Repeat until you are done.

    for(int i = 0; i < chunkArray.size(); i++){
        //copy 512 bytes from file1 to file2 starting at the chunkArray[i]th character
       input.seekg(chunkArray[i]);
       char chunk[512];
       input.read(chunk, 512);
    
       // Deal with error, if there is one.
       if (!input )
       {
       }
    
       // Process the data.
    }