#include <fstream>
#include <vector>
#include <string>
#define BUF_SIZE 512
/* Save the last 'n_lines' lines of 'filename' into vector 'dest'.
* ignore_last_line is useful for \n-terminated files.
* Function returns number of written lines or -1 on error.
*/
int tail(std::string filename, int n_lines, std::vector<std::string> *dest, bool ignore_last_line)
{
int length = ignore_last_line ? (n_lines + 1) : n_lines;
int count = 0;
char buf[length][BUF_SIZE];
std::ifstream fin;
fin.open(filename.c_str(), std::ifstream::in);
if(!fin.good())
return -1;
while(!fin.eof()) {
fin.getline(buf[count % length], BUF_SIZE);
/*
if(fin.fail() && !fin.eof()) {
// fin.fail() is set if either the current bufs is longer than BUF_SIZE-1 characters
// or if an EOF mark is found before another newline. The latter is responsible for the blank
// line at the end of the output. Try ignore_last_line = true.
}
*/
count++;
}
fin.close();
int start = (count < length) ? 0 : count;
int stop = (count < length) ? count : (count + length);
if(ignore_last_line) stop--;
for(int i = start; i < stop; i++)
dest->push_back(buf[i % (length)]);
return ((count < n_lines) ? (ignore_last_line ? (count - 1) : count) : n_lines);
}