【问题标题】:Reading a char array from a text file从文本文件中读取 char 数组
【发布时间】:2018-12-23 05:44:29
【问题描述】:

我有一个函数:

uintptr_t FindPattern(HANDLE hProcess, uintptr_t start, uintptr_t end, char *pattern, char *mask);

当我这样称呼它时,就可以了:

uintptr_t found = FindPattern(hProcess, START, END, "\x89\x41\x24\xE9\x00\x00\x00\x00\x8B\x46\x00\x6A\x00\x6A\x00\x50\x8B\xCE\xE8", "xxxx????xx?xxxxxxxx");

现在,我将模式和掩码存储在一个文本文件中,将它们作为字符串读取,然后将它们转换回 char,但它不再起作用:

char* tmp1 = new char[pattern.length() + 1];
strncpy(tmp1, pattern.c_str(), pattern.length());
tmp1[pattern.length()] = '\0';

char* tmp2 = new char[mask.length() + 1];
strncpy(tmp2, mask.c_str(), mask.length());
tmp2[mask.length()] = '\0';

uintptr_t found = FindPattern(hProcess, START, END, tmp1, tmp2);

delete[] tmp1;
delete[] tmp2;

就我所见,掩码没问题,但我遇到了图案问题。

我想我必须取消“\”或者将它们加倍(“\\”)。

【问题讨论】:

  • 你能分享FindPattern函数的代码吗?
  • 您发布的代码是正确的。该错误在其他地方,可能在FindPattern 或者可能在阅读代码中。
  • strncpy(tmp1, pattern.c_str(), pattern.length());nul-terminate tmp1。来自strncpy 的手册页“警告: 如果 src 的前 n 个字节中没有空字节,则放在 dest 中的字符串不会以空值结尾。” (强调原文,man 3 strncpy)要修复,请使用pattern.length() + 1,或仅使用strcpy

标签: c++ arrays char


【解决方案1】:

问题在于"\x89\x41\x24\xE9\x00\x00\x00\..." 是 C++ 源代码中字符串文字的表示法。该符号仅在作为源代码的一部分时才具有特殊含义。编译器将其解释为具有值0x890x41 等的字节序列。

如果您将其原样复制到文本文件中,则文件中真正拥有的是以下字节序列:\x89\x4

如果您想要的字节序列不是有效文本,则不能将其存储在文本文件中。您必须使用例如十六进制编辑器制作一个二进制文件,或者您应该选择一种文本表示形式并在读入时对其进行转换。

例如,您可以将其表示为用空格分隔的整数:

137 65 36 233

然后读入:

std::string result;
std::fstream myfile("D:\\data.txt", std::ios_base::in);

int a;
while (myfile >> a)
{
    result += static_cast<char>(a);
}

std::cout << result << std::endl;

【讨论】:

    猜你喜欢
    • 2015-07-07
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    • 2012-10-20
    • 2011-05-21
    • 1970-01-01
    相关资源
    最近更新 更多