代码之家  ›  专栏  ›  技术社区  ›  Nnn

中间C:大文件中的字符串搜索

  •  1
  • Nnn  · 技术社区  · 7 年前

    我正在编写一个“C”代码,将捕获的数据包的TCP负载存储在一个文件中(每个数据包的负载由多个“\n”字符分隔)。使用C,是否可以在捕获所有数据包后在文件中搜索特定字符串?

    P、 S:文件可能非常大,这取决于捕获的数据包的数量。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Fabio_MO    7 年前

    逐行读取文件并使用strstr进行搜索。

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    int main(void)
    {
    FILE * fp;
    char * line = NULL;
    size_t len = 0;
    ssize_t read;
    char * pos;
    int found = -1;
    
    fp = fopen("filename", "r");
    if (fp == NULL)
        exit(EXIT_FAILURE);
    
    while ((read = getline(&line, &len, fp)) != -1) 
       {
          pos = strstr(line,"search_string");
          if(pos != NULL)
          {
              found = 1;
              break;
          }
       }
    
    if(found==1)
        printf("Found");
    else
        printf("Not Found");
    
    fclose(fp);
    
    if (line)
        free(line);
    
    exit(EXIT_SUCCESS);
    }