从文件中读取最后N行

问题描述:

我试图让这段代码从文件中读取一行,但它不起作用。我想知道你们中的一个人是否可以帮助我。它将读取我可以稍后配置的最后5行,但现在我只是想让它读取最后一行。从文件中读取最后N行

#include <stdlib.h> 
#include <stdio.h> 
#include <ctype.h> 
#include <string.h> 

int main() { 
    FILE *myfile = fopen("X:\\test.txt", "r"); 
    int x, number_of_lines = 0, count = 0, bytes = 512, end; 
    char str[256]; 

    do { 
     x = fgetc(myfile); 
     if (x == '\n') 
      number_of_lines++; 
    } while (x != EOF); //EOF is 'end of file' 

    if (x != '\n' && number_of_lines != 0) 
     number_of_lines++; 

    printf("number of lines in test.txt = %d\n\n", number_of_lines); 

    for (end = count = 0; count < number_of_lines; ++count) { 
     if (0 == fgets(str, sizeof(str), myfile)) { 
      end = 1; 
      break; 
     } 
    } 

    if (!end) 
     printf("\nLine-%d: %s\n", number_of_lines, str); 

    fclose(myfile); 
    system("pause"); 
    return 0; 
} 
+3

刚刚看过用'与fgets线()'。当你得到EOF指示时,最后一行在缓冲区中。当你需要最后N行时,保持一个N行数组并旋转列表直到你到达EOF。 –

在这里你读取所有行成圆形的线缓冲器及打印最后5行,当文件的末尾已经达到了一个简单的解决方案:

#include <stdio.h> 

int main(void) { 
    char lines[6][256]; 
    size_t i = 0; 
    FILE *myfile = fopen("X:\\test.txt", "r"); 

    if (myfile != NULL) { 
     while (fgets(lines[i % 6], sizeof(lines[i % 6]), myfile) != NULL) { 
      i++; 
     } 
     fclose(myfile); 
     for (size_t j = i < 5 ? 0 : i - 5; j < i; j++) { 
      fputs(lines[j % 6], stdout); 
     } 
    } 
    return 0; 
} 
+0

@JaredDuffey:这个答案对你有帮助吗? – chqrlie

+0

抱歉,超级迟到的回复...但是,这确实解决了我所有的问题! – Jared

只是做一个for或while循环读取所有文件(使用的fscanf),当读数得到您想要的行,你把它保存到一个变种。