Q:

How to read the last but one line from a file?

I'm creating an application, which has to get some data from text files. The problem is, that the data i need is in the last but one line in the text file. Is there a way to read the last but one line somehow? I only need the last but one lines content. Could someone help me?
Thanks

A:

Read the whole file, keeping two lines, then discard the last one, for example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int secondtolast(char *dst, size_t maxlen, FILE *h) {
  char *line[2];
  int i = 0;

  line[0] = malloc(maxlen);
  if (!line[0]) return 1;
  *line[0] = 0;
  line[1] = malloc(maxlen);
  if (!line[1]) {
      free(line[0]); /* return memory to the OS */
      return 1;
  }
  *line[1] = 0;

  while (fgets(line[i], maxlen, h)) i = !i;
  strcpy(dst, line[i]);

  free(line[0]);
  free(line[1]);

  return 0;
}

int main(void) {
  char l2[8192];
  if (secondtolast(l2, sizeof l2, stdin)) {
    fprintf(stderr, "no memory");
  }
  printf("second to last line: %s", l2);
  return 0;
}

