Search code examples
cfopengetlineplaintextstrncmp

Obtain lines of a file beginning with a prefix


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));
  }

Solution

  • 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)));
    }