简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM