c - 如何从 C 文件中读取最后 n 行

标签 c algorithm data-structures

这是一道微软面试题。

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/

相关文章:

c - linux下gcc显示当前编译文件名

c - 如果有的话,编码在什么时候开始在 C 中发挥作用?那么如何正确打印字符串呢?

java - 我的校验和算法有什么问题?

c++ - 使用std::forward_list的队列实现返回错误

python - 用 Python 表示图(数据结构)

c - Arduino Uno 上的原型(prototype)线程/多线程

c - 返回函数指针类型

python - Karatsuba 算法适用于小数但不适用于大数,不明白为什么

java - 算法 - 具有较少元素的最大左子数组

c++ - 在优于 O(n) 的时间内找到链表中条目的索引