Hello everyone. I am trying to work through a programming challenge in my c++ book. I have gotten it to work, but i kind of cheated by looking at the file. I am going to past the entire code so i can be compiled, but the main problem i am having is with reading the last line of a file only.

#include <iostream>
#include <fstream>
using namespace std;

void dispJoke ( fstream& );
void dispPunchLine ( fstream& );

int main()
{
	fstream joke ( "joke.txt", ios::in );
	fstream punch ( "punchline.txt", ios::in );

	if ( !joke )
	{
		cout << "Erorr opening file, joke.txt";
		return 0;
	}
	else if ( !punch )
	{
		cout << "Erorr opening file, punchline.txt";
		return 0;
	}

	dispJoke(joke);
	system("pause");
	dispPunchLine(punch);

	joke.close();
	punch.close();

	return 0;
}
void dispJoke ( fstream& joke )
{
	char data[256];
	joke.getline ( data, 256 );
	while ( !joke.eof() )
	{
		cout << data << endl;
		joke.getline ( data, 256 );
	}
}
void dispPunchLine ( fstream& punch )
{
	char data[256];

	punch.seekg(-35L, ios::end );
	punch.getline ( data, 256, '.' );
	while ( !punch.eof() )
	{
		cout << data << endl;
		punch.getline ( data, 256, '.' );
	}
}

the contents of file punchline.txt are:

asfasdfasdfasdfsdf
asdfasdfsadfsadfsadf
asdfsadfsdfsdf
"I can't work in the dark," he said.

I was trying to use the seekg member function. Am i thinking the right way about this? How do i (if i didnt look at the file) determine where to start printing the data if all i want is the last line, not the "garbage" in this test file. Any advice is much appreciated! Thank you

Jason

The while statement is incorrect. The eof() function doesn't work the way you think it does.

while( joke.getline(data, 256) )
{
  // blabla
}

After the above loop finishes data will contain the last line of the file.

This article has been dead for over six months. Start a new discussion instead.