这是一道微软面试题。
Read last n lines of file using C (precisely)
好吧,有很多方法可以实现这一点,其中很少有:
-> 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.
例如,如果文件中有 10 行并且想要读取最后 3 行。然后我们可以创建一个缓冲区数组作为 buf[3][] 并且在运行时将继续以循环方式分配和释放缓冲区直到我们到达最后一行并保留一个计数器以了解数组的当前索引。
如果上述任何方法可以帮助我获得正确答案或任何其他流行的方法/方法来解决此类问题,任何人都可以帮助我提供更优化的解决方案或至少指导我。
最佳答案
您可以使用队列并存储在此队列中看到的最后 n 行。当您看到 eof 时,只需打印队列即可。
另一种方法是从文件末尾到开头读取 1024 字节的 block 。当您找到 n
\n
个字符时停止并打印出最后的 n
行。
关于c - 如何从 C 文件中读取最后 n 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15216223/