hi, i have this problem about reading the file's content from the back
Write a program that asks the user for the name of a file. The program should display
the last 10 lines of the file on the screen (the tail of the file). If the file has fewer than
10 lines, the entire file should be displayed, with a message indicating the entire file
has been displayed.
so i tried to make a simple program first, the program reads all the line in the file, starting from the last line and so on, but it doesnt work well, i dont know the what the problems are, anyone can help?
here's my code
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
string line;
char ch;
vector<long>numByte; //to store each line's size
int count = 0, acc = 0;
fstream file("test.txt", ios::in);
while(getline(file, line))
{
numByte.push_back(line.size()); /storing each line's size
count++; //getting numbers of line
}
file.clear(); //clear end of the file
count -= 1;
acc = numByte[count]; // getting starting read byte for seekg
for(int index = 0; index < count; count--)
{
file.seekg((acc * -1), ios::end); //set read point starting from last line and so on
file.clear(); //clear end of the file
getline(file, line); //get each line's content and store it
cout<<line<<endl;
acc += numByte[count]; //for starting read point for seekg
}
}
anyone can help me fix the code? or give me any tips / ideas how to do read file's content starting from the last line..
i know it would have been easier if i store all the lines into a string array then just show it to the screen from the last array, but i want to try something new which is by reading from the last line using seekg function..
sorry for the bad english