cbinaryhexhex-editors

How can I write hexadecimal data in the file so that additional data is not written (like hexeditors)?


I want to make something like a small hex editor for my project.

so i wrote a function like this(to replace the original code with the new code):

int replace(FILE *binaryFile, long offset, unsigned char *replaced, int length) {
    if (binaryFile != NULL) {
        for (int i = 0; i < length; i++) {
            fseek(binaryFile, offset + i, SEEK_SET);
            fwrite(&replaced[i], sizeof(replaced), 1, binaryFile);
        }
        fclose(binaryFile);
        return 1;
    } else return -1;
}

So I wrote this code to test the function and sent it to address 0x0:

unsigned char code[] = "\x1E\xFF\x2F\xE1";

and i got this hexadecimal result:

1e ff 2f e1 00 10 2b 35 ff fe 07 00

But I don't need data after E1 (00 10 2b 35 ff fe 07 00)

How can I write the function so that only the data sent to the function is stored?


Solution

  • sizeof(replaced) is wrong. replaced is a unsigned char *, so that's not the size you want.

    You probably want sizeof(unsigned char) or sizeof(*replaced).

    Currently, you end up writing eight times too much.

    Note that you could also write in a single step:

    if (binaryFile != NULL) 
    {
        fseek(binaryFile, offset, SEEK_SET);
        fwrite(replaced, sizeof(unsigned char), length, binaryFile);
    }