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:
- append (4,9);
- 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 o开发者_StackOverflowbj, 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. :)
Instead of closing and reopening file this way (I'm not sure if this operation will reset file position you require!) why not use std::fstream::seekg()
and just "rewind" the file to beginning
infile.seekg(0, ios::beg)
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/
精彩评论