获取以前缀开头的文件行

Obtain lines of a file beginning with a prefix

我正在尝试检测我的明文中哪些行以 "linePrefix" 开头。使用上面的代码,即使出现巧合,strcmp 也永远不会 returns 0。有人知道我在哪里失败了吗?

  const char PREFIX[] = {"linePrefix"};
  FILE *fp;
  char *line = NULL;
  char *aux = NULL;
  aux = (char *) malloc(16);
  size_t len = 0;
  ssize_t read;
  char path[] = {/*path*/};

  fp = fopen(path, "r");

  while ((read = getline(&line, &len, fp)) != -1) {
    strncpy(aux, line, 15);
    printf("strcmp: %i\n, strcmp(aux, PREFIX));
  }

您忘记在 aux 上添加字符串终止符:

strncpy(aux, line, 15);
aux[15] = `[=10=]`;

请注意,有一种更简单的方法可以在不需要复制字符串的情况下进行比较。直接和line的开头比较就可以了:

while ((read = getline(&line, &len, fp)) != -1) {
  printf("strcmp: %i\n, strncmp(line, PREFIX, strlen(PREFIX)));
}

这些行很可能超过 15 个字符,在这种情况下 strncpy() 会中断。 strncpy 表现为:

If the array pointed to by s2 is a string that is shorter than n characters, null characters are appended to the copy in the array pointed to by s1, until n characters in all have been written.

也就是说,如果没有空间,strncpy不会null终止程序,导致程序死机。因此,避免使用strncpy(),它是程序员经常不能正确使用的危险函数。

更好的代码:

size_t length = strlen(line);

if(length > MAX_LENGTH)
{
  length = MAX_LENGTH;
}

memcpy(aux, line, length);
aux[length] = '[=10=]';