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);
}
fstat()? - EOFfstat()is not in the C-standard, but in POSIX, though I am almost certain there are equivalents in other OS-families. To usefstat(), you create astruct stat xand then callf-/l-/stat()on the file-desciptor/-name andx. Then you look atx.st_size. - EOF