加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C:在文件中搜索字符串

发布时间:2020-12-16 10:27:10 所属栏目:百科 来源:网络整理
导读:如果我有: const char *mystr = "cheesecakes";FILE *myfile = fopen("path/to/file.exe","r"); 我需要编写一个函数来确定myfile是否包含任何mystr的出现.谁能帮助我?谢谢! 更新:事实证明我需要部署的平台没有memstr.有谁知道我可以在我的代码中使用的免
如果我有:

const char *mystr = "cheesecakes";
FILE *myfile = fopen("path/to/file.exe","r");

我需要编写一个函数来确定myfile是否包含任何mystr的出现.谁能帮助我?谢谢!

更新:事实证明我需要部署的平台没有memstr.有谁知道我可以在我的代码中使用的免费实现?

解决方法

如果您无法将整个文件放入内存,并且您可以访问GNU memmem()扩展,那么:

>尽可能多地读入缓冲区;
>使用memmem(buffer,len,mystr,strlen(mystr)1)搜索缓冲区;
>丢弃除缓冲区的最后一个strlen(mystr)字符之外的所有字符,并将它们移到开头;
>重复直到文件结束.

如果你没有memmem,那么你可以使用memchr和memcmp在纯C中实现它,如下所示:

/*
 * The memmem() function finds the start of the first occurrence of the
 * substring 'needle' of length 'nlen' in the memory area 'haystack' of
 * length 'hlen'.
 *
 * The return value is a pointer to the beginning of the sub-string,or
 * NULL if the substring is not found.
 */
void *memmem(const void *haystack,size_t hlen,const void *needle,size_t nlen)
{
    int needle_first;
    const void *p = haystack;
    size_t plen = hlen;

    if (!nlen)
        return NULL;

    needle_first = *(unsigned char *)needle;

    while (plen >= nlen && (p = memchr(p,needle_first,plen - nlen + 1)))
    {
        if (!memcmp(p,needle,nlen))
            return (void *)p;

        p++;
        plen = hlen - (p - haystack);
    }

    return NULL;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读