C:寻找在一个文件中的字符串 [英] C: searching for a string in a file

查看:111
本文介绍了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 。有谁知道一个自由的实现,我可以在我的code使用的?

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(缓冲,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 ,那么你可以用它实现在纯C 了memchr memcmp ,就像这样:

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天全站免登陆