简体   繁体   中英

Reading a char array from a text file

I have a function:

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

When I call it like this, it's OK:

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");

Now, I'm storing pattern and masking in a text file, reading these as string and then convert them back to char, but it's no longer working:

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;

For what I see, mask is OK but I got a problem with pattern.

I think I have to suppress "\\" or maybe doubling them ("\\\\").

The problem is that "\\x89\\x41\\x24\\xE9\\x00\\x00\\x00\\..." is a notation for a string literal in C++ source code. This notation only has special meaning when it is part of the source code. The compiler interprets it as a sequence of bytes with value 0x89 , 0x41 , etc.

If you copied this as is to a text file, what you really have in the file is this sequence of bytes: \\ , x , 8 , 9 , \\ , x , 4 , etc

If the byte sequence that you want is not valid text, you cannot store it in a text file. You will have to make a binary file with for instance a hex editor, or you should choose a text representation and convert it when you read it in.

You could for instance represent it as integers separated by spaces:

137 65 36 233

And then read it in with:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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