Thursday, April 3, 2014

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

Problem
Write a method to print the last K lines of an input file using C++.
Solution
Method 1 - Slow and fast file pointer pointer
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.

#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();
}

Method 2  - Read whole file and then print
This is the approach we can follow:
  1. Have an array of strings with size K.
  2. Read the first line and store into the array
  3. Continue reading till the array is full, put it in I % K location, where is the Ith line.
  4. Once the array is full delete the first entry OR replace the first line with the current line,  so that you can enter new line Repeate step 3 and 4 till the file is finished reading.
 
 
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;
}

References
http://tianrunhe.wordpress.com/2012/04/10/print-the-last-k-lines-of-a-file-using-c/
http://stackoverflow.com/questions/5794945/print-out-the-last-10-lines-of-a-file

0 comments:

Post a Comment