Search code examples
cbinaryconcatenationfopenfseek

How can I carve out one binary file from a concatenated binary


Basically I'm combining two binaries using the "cat" command on Linux. And I want to be able to separate them again using C this is the code I got so far

int main(int argc, char *argv[]) {

    // Getting this file 
    FILE *localFile = fopen(argv[0], "rb");

    // Naming a new file to save our carved binary
    FILE *newFile = fopen(argv[1], "wb+");

    // Moving the cursor to the offset: 19672 which is the size of this file
    fseek(localFile, 19672, SEEK_SET);

    // Copying to the new file
    char ch;
    while ( ( ch = fgetc(localFile) ) != EOF ) {
        fputc(ch, newFile);
    }
}

Solution

  • Assuming that you already know where the second file starts. You can proceed as follows. (This is bare minimal)

    #include <stdio.h>
    #include <unistd.h>
    
    int main()
    {
        FILE* f1 = fopen("f1.bin", "r");
        FILE* f2 = fopen("f2.bin", "w");
    
        long file1_size = 1;
    
        lseek(fileno(f1), file1_size, SEEK_SET);
    
        char fbuf[100];
        int rd_status;
    
        for( ; ; ) {
            rd_status = read(fileno(f1), fbuf, sizeof(fbuf));
    
            if (rd_status <= 0)
                break;
            write(fileno(f2), fbuf, rd_status);
        }
    
        fclose(f1);
        fclose(f2);
        return 0;
    }
    

    Input File -- f1.bin

    1F 2A 
    

    Output File -- f2.bin

    2A
    

    Please, modify the file names and file sizes according to your example.