简体   繁体   English

如何从文件中读取最后一行?

[英]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 . 最后读取最后一行但存储在变量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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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