C: 在文件中搜索字符串 [英] C: searching for a string in a file

查看:29
本文介绍了C: 在文件中搜索字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有:

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

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

I need to write a function to determine whether myfile contains any occurrences of mystr. Could anyone help me? Thanks!

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

UPDATE: So it turns out the platform I need to deploy to doesn't have memstr. Does anyone know of a free implementation I can use in my code?

推荐答案

如果您不能将整个文件放入内存中,并且您可以访问 GNU memmem() 扩展名,然后:

If you can't fit the whole file into memory, and you have access to the GNU memmem() extension, then:

  • 尽可能多地读入缓冲区;
  • 使用 memmem(buffer, len, mystr, strlen(mystr) + 1) 搜索缓冲区;
  • 丢弃缓冲区的最后一个strlen(mystr)字符,并将它们移到开头;
  • 重复直到到达文件末尾.
  • Read as much as you can into a buffer;
  • Search the buffer with memmem(buffer, len, mystr, strlen(mystr) + 1);
  • Discard all but the last strlen(mystr) characters of the buffer, and move those to the start;
  • Repeat until end of file reached.

如果您没有 memmem,那么您可以使用 memchrmemcmp 在纯 C 中实现它,如下所示:

If you don't have memmem, then you can implement it in plain C using memchr and memcmp, like so:

/*
 * 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;
}

这篇关于C: 在文件中搜索字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆