首页 > 解决方案 > 在 windows 中使用 memmem() 的实现时遇到问题

问题描述

当我使用该函数时,我只收到 NULL,我做错了什么吗?我正在尝试以二进制方式读取文件,然后找出那里是否有特定的签名

这是我的代码:

#include <stdio.h>
void *memmem(const void *haystack, size_t haystack_len, const void * const needle, const size_t needle_len);
#define TEXT2 "hey"

int main(void)
{   
    unsigned char* buffer = NULL;
    FILE* file = fopen("lol.txt", "rb");

    long bufferLen = 0;

    fseek(file, 0, SEEK_END);
    bufferLen = ftell(file);
    fseek(file, 0, SEEK_SET);

    buffer = (char*)calloc(bufferLen, sizeof(char));


    fread(buffer, sizeof(char), bufferLen, file);
    fclose(file);

    char *pos = memmem(buffer, bufferLen, TEXT2, sizeof(TEXT2));

    if (pos != NULL)
        printf("hey");

    getchar();
    return 0;
}


void *memmem(const void *haystack, size_t haystack_len, const void * const needle, const size_t needle_len)
{
    if (haystack == NULL) return NULL; // or assert(haystack != NULL);
    if (haystack_len == 0) return NULL;
    if (needle == NULL) return NULL; // or assert(needle != NULL);
    if (needle_len == 0) return NULL;

    for (const char *h = haystack; haystack_len >= needle_len; ++h, --haystack_len) 
    {
        if (!memcmp(h, needle, needle_len)) 
        {
            return h;
        }
    }
    return NULL;
}

我试图这样做,但它总是让我返回 null 有什么想法吗?我做错什么了吗?

标签: cwindows

解决方案


char *pos = memmem(buffer, bufferLen, TEXT2, sizeof(TEXT2));
//                                           ^^^^^^^^^^^^^

sizeof "hey"是 4."hey"有类型char[4]

用。。。来代替strlen("hey")

char *pos = memmem(buffer, bufferLen, TEXT2, strlen(TEXT2));

推荐阅读