Question

I want to get the Magic Number from a binary file. For example JPG files have FFD8 for Magic Number in the first bytes. How can I read this ? I want to write a program that check if the file extension response the magic number and if it doesn't to rename the file.

This is what I think it should be, but it doesn't work. It always print different values. I want it to give me the magic number if the file is JPG then - FFD8.

int main()
{
    FILE *f;
    char fName[80];
    char *array;
    long fSize;

    printf("Input file name\n");
    scanf("%s", fName);
    if((f=fopen(fName, "rb"))==NULL)
    {
        fprintf(stderr, "Error\n");
        exit(1);
    }

    fseek (f , 0 , SEEK_END);
    fSize = ftell (f);
    rewind (f);
    array=(char *)malloc(fSize+1);

    fread(array, sizeof(char), 4, f);
    printf("%x", array);
    free(array);
}
Était-ce utile?

La solution

printf("%x", ...) expects an int argument and you are giving it a char *, i.e. a pointer. That is undefined behaviour.

What you probably meant is

printf("%02hhx%02hhx%02hhx%02hhx\n", array[0], array[1], array[2], array[3]);

to print the first 4 characters as hexadecimal numbers. (Thanks to @chux for reminding me about the "hh" modifier, which specifies that the conversion applies to a signed or unsigned char argument.)

(But note that "FFD8" is the hexadecimal notation for two bytes: 0xFF, 0xD8.)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top