HELP - File Preview Problem

Here's the problem I'm working on:
Write a program that asks the user for the name of a text file. The program should display the last 5 lines of the file on the screen. If the file has fewer than 5 lines, the entire file is displayed, with a message that the entire file has been displayed. The program should do this by seeking to the end of the file and then backing up to the fifth line from the end of file.


I've managed to get to the end of the file using

inFile.seekg(0, ios::end);

but I'm stumped as to how I can back up five lines from there. The lines of text vary in size.

All help is welcome.
Last edited on
*Follow-up*

Using text files where the size of the lines are all the same, I was able to use this to make it work for the files with 5 or more lines of text:

1
2
3
inFile.seekg(0, ios::end);
length = inFile.tellg();;
inFile.seekg(-90, ios::end);


OK, let me try to narrow down the help I need with this: Is there a way to search backwards (starting from the end) through a text file for a new line character, and if so, how do you do that?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <vector>
#include <string>
#include <fstream>
#include <iostream>

int main()
{
	std::vector<std::fstream::pos_type> lineIndex ;

	std::ifstream in( "Data.txt" ) ;


	std::fstream::pos_type lnPos = in.tellg() ;

	std::string input ;
	while ( std::getline(in, input) )
	{
		lineIndex.push_back(lnPos) ;
		lnPos = in.tellg() ;
	}
	
	in.clear() ;

	// get 5th line from end:

	in.seekg(lineIndex[lineIndex.size()-5], std::ios::beg) ;
	std::getline(in, input) ;

	std::cout << input << '\n' ;
}
Topic archived. No new replies allowed.