Solution
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
bool create_file_with_n_lines(string outfile, int n)
{
ofstream of;
int i;
of.open(outfile.c_str());
for(i = 0; i < n; i++){
of << "line " << i << endl;
}
of.close();
return true;
}
bool get_last_n_lines(string infile, int n)
{
ifstream instream;
instream.open(infile.c_str());
vector<string> v;
char line[256];
int i = 0;
if(n < 1){
return false;
}
while(!instream.eof()){
instream.getline(line, 256);
cout << line << endl;
if(i < n){
v.insert(v.end(), line);
}
else{
string str = line;
if(str.size() != 0)
v.at(i%n) = line;
}
i ++;
}
cout << "after processing" << endl;
int j;
i --;
if(i > n){
i = i % n;
for(j = i; j < n; j ++){
cout << v.at(j).c_str() << endl;
}
}
for(j = 0; j < i; j ++){
cout << v.at(j).c_str() << endl;
}
return true;
}
int main(int argc, char* argv[])
{
string strfile = "out.txt";
create_file_with_n_lines(strfile,12);
get_last_n_lines(strfile, 5);
return 0;
}
Output
line 0
line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9
line 10
line 11
after processing
line 7
line 8
line 9
line 10
line 11
Problem
Print the last n lines of an text file