GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

how to read last n line from a text file in c language

i am new to c language

and want to know a code for reading a n lines from a file

plz help

asked Jan 27, 2016 by anonymous

1 Answer

As you don't know total number of lines in file, you have to do above things in two steps -

First count total number of lines in file let cnt,  then start reading from (cnt - n)th line.

#include <stdio.h>
#define M 100

int main()
{
	FILE* f;
	f = fopen("data.txt", "r");
	
	int cnt = 0;
	char buf[M];
	
	while(fgets(buf, M, f))
	{
		cnt++;
	}
	
	fseek(f, 0, SEEK_SET);		//	setting the file pointer at starting of file again

	int n = 3;					//	let we want to read last 3 lines
	int t = 0;
	
	while(fgets(buf, M, f))
	{
		t++;
		if(t > cnt - n)
			printf("%s\n", buf);
	}
	
	return 0;
}

 

answered Jan 29, 2016 by utkarsh111
...