我目前有一个文件将新条目附加到当前文件。我想获取最近的5个条目。如何在C中首先读取最后一行?如果可能的话,我想使用fgets命令逐行读取。
感谢您的帮助!
编辑: 例如:
原始档案:
The cat is fast.
Dogs are cool.
I like pie.
期望的输出:
I like pie.
Dogs are cool.
The cat is fast.
答案 0 :(得分:1)
while(fgets(buffer,sizeof(buffer),fp); //go on scanning lines
//Now `buffer` holds the last line of `fp`
答案 1 :(得分:0)
#include <stdio.h>
#define N 5 //number of recent entry
int main(void){
long entry[N+1];//+1 for end of file
int i, index = 0;
FILE *fp = fopen("entry.txt", "r");
char line[128];
for(i=0;i<N+1;++i)
entry[i] = -1L;//initialize to invalid value
do{ //path I : store file position
entry[index++] = ftell(fp);
if(index == N+1)
index = 0;
}while(EOF!=fscanf(fp, "%*[^\n]%*c"));
if(--index < 0)//one back index
index += N+1;
entry[index] = -1L;//for end of file
for(i = 0; i < N; ++i){//get N entry
if(--index < 0)
index += N+1;
if(entry[index] < 0L)
break;//when number of entry < N
fseek(fp, entry[index], SEEK_SET);
fgets(line, sizeof line, fp);
fputs(line, stdout);
}
fclose(fp);
return 0;
}