General C++ Problem


Coder

Still Fresh
Joined
Dec 13, 2006
Messages
84
Age
59
Website
Visit site
I'm writing a Text Viewer (yeah I know there's a few out there, but they don't have the features I want) and have a general problem writing integers to a file.

Now, I'm pretty new to Programming the GP2x and only reasonably conversant in C++, so it's likely to be a problem in the way I've coded it rather than in the C++ libraries.

I'm using the official GP2XSDK.

Here's the code to open the file.

Code:
  vector<int> lines;
  int s;
  fstream idx(pfn.c_str(), ios::in | ios::out | ios::binary );
  idx.read((char*)&s, sizeof(int));
  if (s != cfg.MainFontSize) {
	idx.close();  
	ParseFile();
	fstream idx(pfn.c_str(), ios::in | ios::out | ios::binary );
	idx.read((char*)&s, sizeof(int));	
  }
  idx.read((char*)&s, sizeof(int));
  cfg.CurrentPos = s;
	
  while (!idx.eof()) {
	idx.read((char*)&s, sizeof(int));
	lines.push_back(s);
  }

This works fine, the problem is, I need to update the current position pointer (second integer in the file). I do that like this

Code:
	  if ( done == VK_FX) {
		startline = startline + maxlines; // Page Down
		if (startline > lines.size()) { startline = startline - maxlines;}
		cfg.CurrentPos = startline;
		idx.seekp(sizeof(int));
		idx.write ((char*)&startline, sizeof (int));
		redraw = true;
	  }

The problem is, this doesn't write to the file at all.

If I change the fstream to an ofstream, it does write, but it also truncates the file on opening (even when adding ios::ate to the parameters), so that's not a solution.

I could just rewrite the entire file once when the program exits, but if the power is cut, it wont get written.

So, sorry for the long post, anyone got any idea what I'm doing wrong?
 
OK, figured it out, and it was my coding at fault.

What was happening was I was reading the file until eof, when fstream hits end of file it sets the eof bit and the fail bit.

Once the fail bit is set, no operations on the file will succeed until the failbit is cleared.

The modified code looks like this

Code:
  while (!idx.eof()) {
	idx.read((char*)&s, sizeof(int));
	lines.push_back(s);
  }
  idx.clear(); // <------ Added this line

Now everything works fine.
 
Back
Top