c - 在 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 有什么想法吗?我做错什么了吗?
解决方案
char *pos = memmem(buffer, bufferLen, TEXT2, sizeof(TEXT2));
// ^^^^^^^^^^^^^
sizeof "hey"
是 4."hey"
有类型char[4]
。
用。。。来代替strlen("hey")
char *pos = memmem(buffer, bufferLen, TEXT2, strlen(TEXT2));
推荐阅读
- angular - 将值传递给子组件并将其用作 Angular 中的查询参数
- notifications - 在 Azure DevOps 部署之后按阶段通知指定收件人的最佳方式是什么
- ios - iOS 版本与 iOS sdk
- php - JWT - 第二次刷新后的 TOKEN_EXPIRED
- javascript - 如何解决页面加载时的按键事件?
- jquery - 从日期开始以 HTML 格式显示来自 jQuery/Ajax 的 json 数据
- xamarin - 如何在 Xamarin.iOS 中将 ARGB8888 转换为 420Yp8_CbCr8?
- c++ - 在 Windows IDE 中编写 C++ 代码并在 Linux 终端中编译的有效方法?
- java - 当我将样式表链接到 Thymleaf 页面时,为什么 SpringBoot 会掉线?
- vue.js - v-pre 在带有插槽的自定义组件上