简体   繁体   English

从C中的文件读取字符

[英]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. 我编写了一个简短的C代码,它将打开一个文件,读取前2个字节(2个字符),并将其与2个字符串进行比较。 This is to help in identifying the file type (lets call the first 2 bytes the signature of the file). 这有助于识别文件类型(让我们将前2个字节称为文件签名)。

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. 现在,一旦我从文件中读取了2个字节,我想将其与预定义的签名进行比较,并基于该打印文件类型。

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. 如果我在Windows平台上为可执行文件运行此命令,它将显示为:4a 5d,因为它是MZ签名。

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. 比较签名数组的2个字节与0x4d5a,如果相等,则打印它是可执行文件。

the other way I thought was, compare it with the string, "MZ". 我认为的另一种方法是,将其与字符串“ MZ”进行比较。 but then I need to use fscanf to read the first 2 bytes from the file and store them in a string. 但是然后我需要使用fscanf从文件中读取前2个字节,并将它们存储在字符串中。 Then compare it with the "MZ" signature. 然后将其与“ MZ”签名进行比较。

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" ). 首先,您可能应该以二进制模式( "rb" )打开文件。

As for the reading, you could use fread to read the two first bytes as a single uint16_t , and compare that. 至于读取,您可以使用fread作为单个uint16_t读取前两个字节,然后进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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