954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Help reading data from a file

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

jbrock31
Junior Poster in Training
79 posts since Oct 2008
Reputation Points: 22
Solved Threads: 16
 

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.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

Thanks for the help.

jbrock31
Junior Poster in Training
79 posts since Oct 2008
Reputation Points: 22
Solved Threads: 16
 

AD is correct. Read This

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You