fscanf - Reading characters from a File in C -
here trying do. have written short c code, open file, read first 2 bytes (2 characters) , compare 2 character string. help in identifying file type (lets phone call first 2 bytes signature of file).
now, 1 time have read 2 bytes file, want compare predefined signature , based on print file type.
code:
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { file *fp; char signature[2]; if(argc!=2) { printf("usage: fileio.c <filename>\n"); exit(1); } if((fp=fopen(argv[1],"r"))!=null) { fscanf(fp,"%c %c", &signature[0], &signature[1]); printf("%x %x\n",signature[0],signature[1]); } }
if run executable file on windows platform, show output as: 4a 5d, since mz signature.
now, want this:
compare 2 bytes of signature array with, 0x4d5a, if equal print executable.
the other way thought was, compare string, "mz". need utilize fscanf read first 2 bytes file , store them in string. compare "mz" signature.
it great if can using hex bytes since need perform operation on hex bytes later.
thanks.
#include <stdio.h> #include <stdint.h> int main(int argc, char *argv[]){ file *fp; const char mz_sig[] = {0x4d, 0x5a}; char signature[2]; fp=fopen(argv[1],"r"); fscanf(fp,"%c %c", &signature[0], &signature[1]); printf("%x %x\n", signature[0], signature[1]); if (*(uint16_t*)signature == *(uint16_t*)mz_sig) { printf("match\n"); } homecoming 0; }
c fscanf
No comments:
Post a Comment