0

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);
    }
}
spooky_sec
  • 161
  • 1
  • 10

1 Answers1

1

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.

m0hithreddy
  • 1,752
  • 1
  • 10
  • 17
  • Hi, thanks for answering. Turns out I was doing ```char ch``` where I should've done ```int ch``` How can I mark a question as solved?? :D – spooky_sec May 26 '20 at 18:08
  • Yes, according to ``fgetc()`` man page, it returns the ``unsigned char`` which is typecasted to ``int``. But in less severe cases, you need to avoid reading byte by byte. Because you are performing the disc IO a greater number of times. You should consider using the variants of ``read`` for efficient codes. Pls visit this link, [accepting-answeres](https://stackoverflow.com/help/someone-answers) – m0hithreddy May 26 '20 at 18:13