Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading