如何从C中的文件读取最后n行 [英] how to read last n lines from a file in C

查看:116
本文介绍了如何从C中的文件读取最后n行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个Microsoft面试问题.

使用C(精确)读取文件的最后n行

有很多方法可以做到这一点,其中很少有:

->最简单的方法是,第一遍计算文件中的行数,第二遍显示最后n行.

->或者可以为每行维护一个双向链表,并通过向后遍历链表直到最后一个节点来显示最后n行.

->实现某种排序的尾巴-n fname

->为了进一步优化它,我们可以使用长度为n的双指针,并以循环方式动态存储每一行​​,直到到达文件末尾为止.

例如,如果文件中有10行,并且想读取最后3行.然后我们可以创建一个缓冲区数组buf [3] [],并在运行时继续循环循环分配和释放缓冲区,直到到达最后一行并保持计数器知道数组的当前索引为止.

如果上述方法中的任何一种可以帮助我获得正确的答案或解决此类问题的任何其他流行的方法/方法,谁能帮助我提供更优化的解决方案,或者至少指导我.

解决方案

您可以使用队列并存储在此队列中看到的最后n行.当您看到eof时,只需打印队列即可.

另一种方法是从文件末尾到开头读取一个1024字节的块.当找到 n \ n 个字符并打印出最后的 n 行时停止.

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.

解决方案

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.

这篇关于如何从C中的文件读取最后n行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆