Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read last n lines from a file in C

Its a microsoft interview question.

Read last n lines of file using C (precisely)

Well there could be so many ways to achieve this , few of them could be :

-> Simplest of all, in first pass , count the number of lines in the file and in second pass display the last n lines.

-> Or may be maintain a doubly linked-list for every line and display the last n lines by back traversing the linkedlist till nth last node.

-> Implement something of sort tail -n fname

-> In order to optimize it more we can have double pointer with length as n and every line stored dynamically in a round robin fashion till we reach the end of file.

for example if there are 10 lines in file and want to read last 3 lines. then we could create a array of buffer as buf[3][] and at run time would keep on mallocing and freeing the buffer in circular way till we reach the last line and keep a counter to know the current index of array.

Can anyone please help me with more optimized solution or atleast guide me if any of the above approaches can help me get the correct answer or any other popular approach/method for such kind of questions.

like image 598
Anshul Avatar asked Mar 05 '13 05:03

Anshul


People also ask

How do you print last 10 lines of file?

To look at the last few lines of a file, use the tail command. tail works the same way as head: type tail and the filename to see the last 10 lines of that file, or type tail -number filename to see the last number lines of the file.

How do you check if you are at the end of a line in C?

“how to check end of line in c” Code Answer EOF) { printf("%d",n); //other operations with n.. }


1 Answers

You can use a queue and to store the last n lines seen in this queue. When you see the eof just print the queue.

Another way is reading a blocks of 1024 bytes from the end of file towards the beginning. Stop when you find n \n characters and print out the last n lines.

like image 56
perreal Avatar answered Nov 15 '22 05:11

perreal