怎么把文件以16进制写入文件呢。比如,打开Editplus,打开一个exe文件或者其他,会显示如下:
4D 5A 90 00 03 00 00 00 04 00 00 00 FF FF 00 00
B8 00 00 00 00 00 00 00 40 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00
0E 1F BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68
69 73 20 70 72 6F 67 72 61 6D 20 63 61 6E 6E 6F
74 20 62 65 20 72 75 6E 20 69 6E 20 44 4F 53 20
6D 6F 64 65 2E 0D 0D 0A 24 00 00 00 00 00 00 00
51 13 E2 96 15 72 8C C5 15 72 8C C5 15 72 8C C5
1C 0A 1F C5 1D 72 8C C5 86 3C 14 C5 14 72 8C C5
7A 04 12 C5 14 72 8C C5 7A 04 26 C5 07 72 8C C5
7A 04 10 C5 10 72 8C C5 15 72 8D C5 1B 73 8C C5
7A 04 27 C5 05 72 8C C5 7A 04 16 C5 14 72 8C C5
我们有时候写东西,很希望存入文件的也是这样的东西,这样就涉及到怎么把字符或其他int类型转换成16进制。
#include <stdio.h>
#include <string.h>
int main(int argc,char *argv[])
{
char *strTest = "I am OK!don't worry.";
int strLen=strlen(strTest);
int i=0;
FILE *fp;
if((fp=fopen("C:\\text.txt","wb")) == NULL)
{
printf("file open failed!");
return 0;
}
printf("%d\n",strLen);
while(i<strLen)
{
fprintf(fp,"%02x",strTest[i++]);
}
return 1;
}
上面的代码就是将一段字符串写成每一个字符是16进制的,占两位的。关键函数是fprintf,这个可以再百度上查看很清楚。