读取文件的最后十行

31 篇文章 0 订阅

使用c设计一个方法去打印输出文件的最后十行

5.2 Write a method to print the last ten lines of an input file using C.


SOLUTION

比较笨的办法是记录文件的行数,然后打印最后十行。但是如果文件很大,两次读取文件很费时。所以我们可以用数组存储读取的行数,先读取十行,这时当读取新的一行时将第一个元素覆盖,再读取一行,将第二个元素覆盖。直到读取完文件。

One brute force way could be to count number of lines (N) and then print from N-10 to Nth
line. But, this requires two reads of the file – potentially very costly if the file is large.
We need a solution which allows us to read just once and be able to print the last K lines. We
can create extra space for K lines and then store each set of K lines in the array. So, initially,
our array has lines 0 through 9, then 1 through 10, then 2 through 11, etc (if K = 10). Each
time that we read a new line, we purge the oldest line from the array. Instead of shifting the
array each time (very inefficient), we will use a circular array. This will allow us to always find
the oldest element in O(1) time.
EXAMPLE of Circular Array:
step 1: array = a b c d e f, p = 0
step 2: g b c d e f, p = 2
step 3: g h c d e f, p = 3

step 4: g h i d e f, p = 4

这里每一行用string类型来存储

getline()

简述

原型
istream& getline ( istream &is , string &str , char delim );
istream& getline ( istream& , string& );
参数
is 进行读入操作的输入流
str 存储读入的内容
delim 终结符
返回值
与参数is是一样的
功能
将输入流is中读到的字符存入str中,直到遇到终结符delim才结束。对于第一个函数delim是可以由用户自己定义的终结符;对于第二个函数delim默认为 '\n'(换行符)。
函数在输入流is中遇到文件结束符(EOF)或者在读入字符的过程中遇到错误都会结束。
在遇到终结符delim后,delim会被丢弃,不存入str中。在下次读入操作时,将在delim的下个字符开始读入。

#include<string>//getline包含在string头文件里

string L[K];
int index = 0;
while (!File.eof()) {
L[index % K] = getLine(File); // read file line by line
++index;
}
// if less than ten lines were read, print them all
if (index < 10) {
index = 0;
}
for(int i = 0; i < K; ++i) {
printf(“%s”, L[(index + i) % K]);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值