Print the last k line.

Write a method to print the last K lines of an input file using C++.

C++:
01 void printLastKline(string filename, int k)
02 {
03     ifstream in(filename.c_str());
04     if(in.fail()){
05         cout<<“fail!!!”<<endl;
06         in.clear();
07     }
08     string a;
09     for(int i=0;i<k;i++)
10         getline(in,a);
11 
12     ifstream inn(filename.c_str());
13     if(inn.fail()){
14         cout<<“fail!!!”<<endl;
15         inn.clear();
16     }
17 
18     string b;
19 
20     while(getline(in, a)){
21         getline(inn,b);
22     }
23     while(getline(inn,b)){
24         cout<<b<<endl;
25     }
26 
27 }
Can we just read file once? Yes we can!
C++:
01 void printLastKline(string filename, int k)
02 {
03     int cnt;
04     string *A=new string[k];
05     ifstream in(filename.c_str());
06     if(in.fail()){
07         cout<<“fail!!!”<<endl;
08         in.clear();
09     }
10     int i=0;
11 
12     for(i=0; getline(in, A[i]);i=(i+1)%k){
13         cnt++;
14     }
15     cnt=cnt<k?cnt:k;
16     for(int j=0;j<cnt;j++){
17         cout<<A[(i+j)%k]<<endl;
18     }
19 
20 }
Advertisements
This entry was posted in File operation. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s