Open a png file and read it's hex values in C
c, hex, png
Solution
In order to read the binary bytes from the file use `fread`:
The function fread() reads nmemb elements of data, each size bytes long, from the stream pointed to by stream, storing them at the location given by ptr.
something like:
unsigned char head[8];
fread(head, sizeof(head), 1, dat);
you can check the return value to verify that 8 bytes were actually read.
then compare using memcmp
unsigned char signature[8] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};
if (!memcmp(signature, head, 8))
{
...
}
Problem
I am attempting to read a file with any filetype ending and determining from it's hex values if it is a PNG file. So far I have tried on two different paths but none are working. - With first I read first 16 characters since first 8 hex values determines if it has the right header. Then I try to seperate it and read is as hex value as it was presented in some other thread here. - The other I just want to read first two values and determine if it is hex value to even see if it's working. It is not. code: ``` int IS_PNG_FILE(char *name) { FILE *dat = fopen (name, "rt"); if (dat == NULL) return 1; int data_point; char buf[16], a[16]; fgets(buf, 16, dat); printf("%s\n", buf); int i, b; for (i=0; i<16; i++) { sscanf(&buf[i], "%2x", &b); a[i] = b; i += 2; } printf("%d\n", a); fscanf(dat, "%2x", &data_point); printf("%d\n", data_point); fclose(dat); return 0; } ```