Neon Flash
Neon Flash

Reputation: 3233

Reading characters from a File in C

Here is what I am trying to do. I have written a short C code, which will open a file, read the first 2 bytes (2 characters) and compare it with a 2 character string. This is to help in identifying the file type (lets call the first 2 bytes the signature of the file).

Now, once I have read the 2 bytes from the file, I want to compare it with a predefined signature and based on that print the 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 I run this for an executable file on Windows Platform, it will show the output as: 4a 5d, since it is the MZ signature.

now, I want to do something like this:

compare the 2 bytes of the signature array with, 0x4d5a, if they are equal then print that it is an executable.

the other way I thought was, compare it with the string, "MZ". but then I need to use fscanf to read the first 2 bytes from the file and store them in a string. Then compare it with the "MZ" signature.

It would be great if I can do it using hex bytes since I need to perform some operation on the hex bytes later.

Thanks.

Upvotes: 1

Views: 2194

Answers (2)

perreal
perreal

Reputation: 97938

#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");
  }

  return 0;
}

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409166

To start with, you should probably open the file in binary mode ("rb").

As for the reading, you could use fread to read the two first bytes as a single uint16_t, and compare that.

Upvotes: 0

Related Questions