Hi, i am trying to write a program that would work much like the tail command in UNIX. The idea is to print the last 10 lines of a file. I started off by finding out how many lines were in the file, then attempted to seek to the appropriate line number to as to print the last 10 lines, however i then realised seekg was seeking character by character, not by the lines. How can i seek to a specific line?
Here is my code
#include<iostream>
#include<fstream>
#include <string>
using namespace std;
int main()
{ int lineCount=0;
fstream file;
char filename[10];
string line;
cout << "Enter file name" << endl;
cin >> filename;
file.open(filename);
if(file.good())
{
cout << "file opened successfully" << endl;
string t;
while(getline(file, t, '\n'))
++lineCount;
}
else
{
cout << "Error file does not exist" << endl;
}
file.close();
file.open(filename);
if(file.good())
{
int x = lineCount - 10;
file.seekp (x, ios::beg);
getline (file, line);
cout << line << endl;
while(! file.eof() )
{
getline (file,line);
cout << line << endl;
}
}
file.close();
return 0;
}