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.
source
share