这将打开一个文本文件并使用fgets 读取包含十六进制值的行。 sscanf 格式," /x%x%n" 跳过任何空格,扫描/,然后扫描x,一个十六进制值,并通过%n 保存offset 中处理的字符数。 used 和 offset 允许 sscanf 通过 hex 缓冲区工作。
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[])
{
FILE *fp = NULL;
char hex[1024] = "";
int each = 0;
size_t used = 0;
size_t offset = 0;
if ( ( fp = fopen ( "shcodes", "r")) == NULL) {
printf ( "could not open file\n");
return 1;
}
while ( fgets ( hex, sizeof ( hex), fp)) {
used = 0;
//work through the string as long the format is matched
while ( ( sscanf ( hex + used, " /x%x%n", &each, &offset)) == 1) {
printf ( "sscanf this int %d as hex %x\n", each, each);
used += offset;
}
}
fclose ( fp);
return 0;
}
使用的文本文件是
/xff/xff/xff/xff/xff/xff/xff/xff/xff/xff/xff/xff/xff/xff/xff
/x0f/x1f/x2f/x3f/x4f/x5f/x6f/x7f/x8f/x9f/xaf/xbf/xcf/xff/xff
/x01/x11/x21/x31/x41/x51/x61/x71/x81/x91/xa1/xb1/xc1/xf1/xff
这应该适用于二进制文件。 fread 是读取二进制数据的更好选择。 bytes 将存储读取的字节数。
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[])
{
FILE *fp = NULL;
unsigned char hex[1024] = "";
int each = 0;
size_t bytes = 0;
if ( ( fp = fopen ( "shcodes.bin", "rb")) == NULL) {
printf ( "could not open file\n");
return 1;
}
//loop as long as there are bytes to read
while ( ( bytes = fread ( &hex, 1, 1024, fp)) > 0) {
for ( each = 0; each < bytes; each++) {
printf ( "read this char as int %u and as hex %x\n", hex[each], hex[each]);
}
}
fclose ( fp);
return 0;
}