2
votes

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);
}
1
Is there any reason you feel compelled to find the size of the entire file, and make a buffer large enough to hold it, when really you only care for and copy four bytes? And if so, do you realize the file system will happily tell you the file size with a simple fstat()? - EOF
I use binary files for first time, so I wanted to try something new. However, can you tell me more about fstat() because I can't find anything about it. - user3476022
Well, fstat() is not in the C-standard, but in POSIX, though I am almost certain there are equivalents in other OS-families. To use fstat(), you create a struct stat x and then call f-/l-/stat() on the file-desciptor/-name and x. Then you look at x.st_size. - EOF

1 Answers

2
votes

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.)