简体   繁体   中英

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

Here is a quick and dirty code. It reads all lines to get the number of all lines, rewinds the file to the beginning and again reads lines until the last but two. Finally the last but one line is read and stored in the variable lastLineButOne .

#include <stdio.h>
#define BUF 255

int getNoOfLines(FILE *f) {
    int ctr=0;
    char temp[BUF];
    while(fgets(temp,BUF,f) != NULL)
        ctr++;
    return ctr;
}

int main() {
    int i;
    FILE *f=fopen("apps.txt","r");
    char lastLineButOne[BUF];
    char temp[BUF];
    int noOfLines=getNoOfLines(f);
    rewind(f);
    for(i = 0; i < noOfLines-2; i++) {
        fgets(temp,BUF,f);
    }
    fgets(lastLineButOne,BUF,f);
    printf("%s",lastLineButOne);
    fclose(f);
    return 0;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM