I used a file which had 15 lines with 2 characters each and hence assumed the size of the file to be around 44 bytes but, using the tellg function, the size is shown as 58. Furthermore, I accumulated an array of all the positions the code was identifying a newline character and they were all consecutive and hence confirmed this doubt. Thank you!
//Tailfile - This program accepts a file and prints the last 10 lines.
//This function determines the number of lines and how to display it
int lineidentifier(fstream&tailfile,long& position)
{
tailfile.seekg(0,ios::end);//sets the read position at the end of file.
long n=0;//counter for the number of lines
long i=tailfile.tellg();//counter for the number of characters set to
//thenumber of bytes in the file and hence, the end.
char ch;//To hold and check the character.
while(n<10&&i>=0)//conditions are as long as the number of characters
//are not exhausted or the number of lines
{
tailfile.seekg(i, ios::beg);//sets the read position to the end of
//the file by using the number of characters and the file
//mode as the beginning.
cout<<"1. "<<i<<endl;//DEBUGGING EXTRA
tailfile.get(ch);//Reads the content at i
tailfile.clear();//clears the eof flag set by the first iteration
//because we reach the end of the file.
cout<<"2. "<<i<<endl;//DEBUGGING EXTRA
if(ch=='\n')//if the character received is the newline character
//leading to us regarding it as a line has been identified.
{
n++;//Increment n accordingly.
position=i;//The position is the byte i is at before the
//character was read, hence the position of the character.
cout<<position<<endl;//DEBUGGING EXTRA
cout<<ch<<endl;//DEBUGGING EXTRA
i--;
}
i--;
cout<<"4. "<<i<<endl;//DEBUGGING EXTRA
}
cout<<i<<endl;//DEBUGGING EXTRA
if(i<=1)//Using the position of i to indicate whether the file has more
//than 10 lines. If i is less than 1, it has reached the
//beginning of the file
return 0;
else
return 1;
}