讀取文件到內存緩衝區,使用 memmem (GNU 擴展) 或手寫二進制安全查找。
#include
#include
#include
// 簡易 memmem 實現 (不依賴 GNU)
void* memmem(const void* haystack, size_t haystack_len, const void* needle, size_t needle_len) {
if (needle_len == 0) return (void*)haystack;
const unsigned char* h = haystack;
const unsigned char* n = needle;
for (size_t i = 0; i <= haystack_len - needle_len; ++i) {
if (h[i] == n[0] && memcmp(h + i, n, needle_len) == 0)
return (void*)(h + i);
}
return NULL;
}
int main() {
const unsigned char pattern[] = {0x89, 0x90, 0x91};
FILE* f = fopen("c:\\1.exe", "rb");
fseek(f, 0, SEEK_END);
long len = ftell(f);
fseek(f, 0, SEEK_SET);
unsigned char* buf = malloc(len);
fread(buf, 1, len, f);
fclose(f);
void* pos = memmem(buf, len, pattern, sizeof(pattern));
if (pos) {
printf("Found at offset: 0x%lX\n", (unsigned char*)pos - buf);
} else {
printf("Not found\n");
}
free(buf);
return 0;
}