0

I am trying to detect which lines of my plaintext start with "linePrefix". Using the code above, even when there is a coincidence, strcmp never returns 0. Does anyone know where am I failing?

  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));
  }
qwerty
  • 486
  • 1
  • 11
  • 37

2 Answers2

4

You forgot to add the string terminator on aux:

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

Note that there is a simpler way to do the comparison where you don't need to copy the string. Just compare with the beginning of line directly:

while ((read = getline(&line, &len, fp)) != -1) {
  printf("strcmp: %i\n, strncmp(line, PREFIX, strlen(PREFIX)));
}
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
  • Good suggestion, though instead of `strlen(PREFIX)` use `sizeof(PREFIX)-1`. – Lundin Aug 13 '15 at 11:46
  • @Lundin That'll work as long as PREFIX is declared as an array. – Klas Lindbäck Aug 13 '15 at 12:03
  • @KlasLindbäck Any reason why it wouldn't be? You may as well write `sizeof("linePrefix")-1` but that would make the code ugly. – Lundin Aug 13 '15 at 12:05
  • `const char *PREFIX = "tag"` would break it. On the other hand, if the optimizer doesn't replace the strlen call with a constant and performance is crucial, then it's definitely worth using `sizeof` to shave off an unnecessary length count. – Klas Lindbäck Aug 13 '15 at 12:13
0

Most likely, the lines are longer than 15 characters, in which case strncpy() breaks. strncpy behaves as:

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.

In other words, if there is no room, strncpy will not null terminate the program, causing it to crash and burn. Therefore, avoid strncpy(), it is a dangerous function that programmers often fail to use correctly.

Better code:

size_t length = strlen(line);

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

memcpy(aux, line, length);
aux[length] = '\0';
Lundin
  • 195,001
  • 40
  • 254
  • 396