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,那么你可以使用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;
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
