所以,我正在构建一个程序,它应该修改二进制文件中特定数量的字节。您首先输入二进制文件,然后是您希望替换十六进制指令的偏移量,然后是字节本身。
例子:
我加载 example.exe
我指定偏移量 0
(文件开头)
我指定十六进制指令:4D FF 33 FD FE
该文件的前 5 条指令应替换为我提供的指令。我使用 fwrite
进行修改,使用 scanf
获取偏移量和十六进制指令,但是,我找不到将它们实际存储为十六进制的方法。 fwrite 实际上将 4D FF 33 FD FE
作为文本而不是十六进制写入二进制文件中。我假设我首先将它们错误地保存在 char
中。我是 C 的新手,所以我在网上找到的东西并没有真正帮助。
这是我的代码:
scanf("%ld",&offset_ed);//get the offset from the user.
fseek(f, offset_ed, SEEK_SET);
printf("Specify HEX bytes to be written to the binary: ");
scanf("%s\n", &hexes);
fwrite (hexes , sizeof(char), sizeof(hexes), f);
fclose (f);
其中hexes是一个char hexes;
最佳答案
总体思路如下。
不要使用 scanf()
,使用 fgets()
读取用户输入的 行。
省略了错误检查(用//** 注释)
char buf[100]; // Use some reasonable upper bound of expected user input.
puts("prompt for input");
fgets(buf, sizeof buf, stdin); // **
offset_ed = strtol(buf, NULL, 10); // **
fseek(f, offset_ed, SEEK_SET); // **
puts("prompt for input");
fgets(buf, sizeof buf, stdin); // **
size_t byte_count = 0;
unsigned char hexes[(sizeof buf)/2] = 0; // place to save the "hex bytes"
int n = 0;
unsigned byte;
现在解析字符串以查找十六进制输入。
// Use "%n" to save the offset of the scan to later update `p`
// Robust code would use `strtol()` for its better error handling
char *p = buf;
while (sscanf(p, "%x %n", &byte, &n) == 1) {
if (byte > 0xFF) Handle_OutOfRange();
hexes[byte_count] = byte;
p += n;
}
if (byte_count == 0) Handle_EmptyUserInput();
if (*p) Handle_ExtraJunkInUserInput();
fwrite (hexes , byte_count, sizeof hexes[0], f); // **
OP 有 scanf("%s\n",...
。"\n"
有问题。scanf()
将阻塞,直到用户在预期输入后输入一些非空白。避免这种情况。
问题可以用scanf()
处理,但它很难看。实际上,代码需要使用 scanf("%*1[^\n]")
等在多个“十六进制”字节之后的某处查找 '\n'
. scanf()
并不是实现整体编码目标的最佳工具。 scanf()
很少是棚子里最锋利的工具。
关于c - 使用 scanf 获取用户输入的十六进制指令并将它们保存在 char 中。 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49029977/