Print the last K lines of a file using C++

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

My initial thoughts:
Using the same idea from this article, we place two pointers to the file, the fast pointer and the slow pointer. The fast pointer is K lines ahead of the slow pointer. When the fast pointer reaches the EOF, we can start to print everything from the slow pointer, all the way to the end.

My initial codes:

#include<iostream>
#include<fstream>
#include<string>
#include <stdlib.h>
using namespace std;

int main(int argc, const char* args[]) {
	ifstream slowIn, fastIn;
	slowIn.open(args[1]);
	fastIn.open(args[1]);
	
	string str;
	int K = atoi(args[2]);
	if(fastIn.is_open()) {
		for(int i = 0; i < K; ++i) {
			getline(fastIn, str);
		}
	}
	
	if(slowIn.is_open()) {
		while(getline(fastIn, str)) {
			getline(slowIn, str);
		}
	}
	
	fastIn.close();
	
	while(getline(slowIn, str)) {
		cout << str << endl;
	}
	
	slowIn.close();
}

Solution:

string L[K];
int lines = 0;
while (file.good()) {
	getline(file, L[lines % K]); // read file line by line
	++lines;
}
// if less than K lines were read, print them all
int start, count;

if (lines < K) {
	start = 0;
	count = lines;
} else {
	start = lines % K;
	count = K;
}

for (int i = 0; i < count; ++i) {
	cout << L[(start + i) % K] << endl;
}
Advertisements

1 Comment (+add yours?)

  1. raspinudo
    Sep 20, 2012 @ 04:00:33

    nice solution, here was mine

    //print last k lines
    #include <iostream>
    #include <deque>
    #include <memory>
    #include <fstream>
    #include <string>
    #include <cstdlib>
    
    int main(int argc, char** argv){
            std::fstream m_file;
            std::string m_temp;
            std::deque<std::string> m_kLines;
    
            if(argc == 3) file.open(argv[1]);
            else { std::cerr << "args error " << std::endl; return -1; }
    
            while(file.is_open() && getline(file, temp)){
                    if(kLines.size() >= atoi(argv[2])) kLines.pop_front();
                    kLines.push_back(temp);
            }
    
            file.close();
    
            for(auto element : kLines) std::cout << element << std::endl;
    }
    

    note* this uses c++11 for each and automatic type deduction.

    Reply

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

%d bloggers like this: