How to read the last n lines from a file in C

Its a microsoft interview question.

Read the last n lines of a file using C (for sure)

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

-> The easiest way, on the first pass, count the number of lines in the file and on the second pass display the last n lines.

-> Or, a doubly linked list can be maintained for each row and display the last n rows, referring back to the linked list to the nth last node.

-> Introduce something like tail -n fname

-> To optimize it more, we can have a double pointer with a length of n and each line dynamically stored in circular mode until we reach the end of the file.

for example, if the file has 10 lines and you want to read the last 3 lines. then we could create a buffer array in the form of buf [3] [], and at runtime it will keep mallocing and free the buffer in a circular way until we reach the last line and keep a counter to find out the current index of the array.

Can someone help me with a more optimized solution or at least guide me if any of the above approaches help me get the right answer or any other popular approach / method for such questions.

+5
source share
3 answers

You can use the queue and save the last n lines visible in this queue. When you see that eof just prints the queue.

- 1024 . , n \n n.

+8

, .

, "\n", , "\n".

(n + 1) th '\n', , , . EOF.

, EOF, n '\n' . EOF.

, , n .

+4

How to use a file with memory mapping and scan the file back? This eliminates the complex work of updating the buffer window each time, if the lines are longer than your buffer space. Then, when you find it \n, push the position onto the stack. This works in O(L), where L is the number of characters displayed. So there is nothing better than that?

+1
source

All Articles