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

Unfortunately, seekg works on bytes not lines. So you have a few options:

  • Store the offsets to the beginning of each line (newline + 1) in the file. seekg to the appropriate value (10 or less from the end) and read the file from there.
  • Store each line in a vector and display only the last ten (or less) items in the vector after reading the file
  • Store only the last ten lines (at most) in a vector and display the entire contents of the vector after reading the file

The value you are seeking to for each count is only the length of that line, not the cumulative length read so far so you are likely not getting results you expect.
[edit] Sorry, I missed the part where you increment the acc variable. So ignore the last part of my post.

hmm ok ill try to store the beginning of each line in the file to seekg, thx for the tips ! it helps alot :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.