tags:

views:

368

answers:

2

I am writing a function which should (if the file already exists) increment the first number by one and append the parameters of the function to the end of the file.

Example:

  1. append (4,9);
  2. append (5,6);

File contents at 1: 1 \n 4 \n 9

File contents at 2: 2 \n 4 \n 9 \n 5 \n 6

int append (int obj, int objType) {

ifstream infile;
infile.open("stuff.txt");

if (infile.fail()){
  infile.close();

  ofstream outfile;
  outfile.open("stuff.txt");
  outfile << 1 << endl << obj << endl << objType;
  outfile.close();
}
else {

  int length = 0;

  while (!infile.eof()){
     int temp;
     infile >> temp;
     length ++;
  }

  infile.close();
  infile.open("stuff.txt");

  int fileContents[length];
  int i = 0;

  while (!infile.eof()){ /*PROGRAM DOES NOT ENTER HERE*/
     infile >> fileContents[i];
     i ++;
  }

  infile.close();

  ofstream outfile;
  outfile.open("stuff.txt");

  fileContents[0] +=1;

  for (i = 0; i < length; i++){
     outfile << fileContents[i] << endl ;
  }

  outfile << obj << endl << objType;


}

The program never enters the second while loop, so the contents are never copied to the array and then into the file. I am unsure exactly what the problem is or how to fix it. Any help would be greatly appreciated. :)

+2  A: 

You haven't done a read to reset the EOF flag yet, so you're still getting the EOF from the previous file.

This isn't the right way to do file input anyway. Try something more like this:

int temp;
while (infile >> temp)
{
    ...
}

And see Neil Butterworth's blog entry that he linked in an earlier question: http://punchlet.wordpress.com/2009/12/01/hello-world/

Fred Larson
I understand that your code is better practice (mia culpa, thank you for pointing it out), however I think that the problem is with the second while, not the one you are referring to?How do I "[do] a read to reset the EOF flag"?Thanks again. :)
Erica
I am referring to the second while. The EOF flag is set or cleared only when the file is read, not opened or closed. So you need to do a read before you can test eof(). In this case, you didn't do a read since you last hit EOF in the previous loop, so eof() returns true, and you never enter the second loop.
Fred Larson
But to read, I wouldn't I need to reset the pointer back to the start of the file?
Erica
Every ">>" operation you do on the stream is a read.
Fred Larson
+2  A: 

Instead of closing and reopening file this way (I'm not sure if this operation will reset file position you require!) why not use

fstream::seekg()

and just "rewind" the file to beginning

infile.seekg(0, ios::beg)

See docs.

Marcin Gil
I have tried adding "infile.seekg(0, ios::beg)" after int i = 0, however the while loop after is still skipped (I assume because, for some reason, the EOF flag is still set).Thank you for your time. :)
Erica
call `infile.clear()` prior calling seekg().
Marcin Gil
It works perfectly. :) Thank you so much!
Erica