0

I seem to be having some issues trying to finish up my C++ Program and would appriciate some help.

At the end of my program I need it too output to a text file. I've tried various methods using fstream and ofstream to check if the file exists and if it does, make a new one, although I've had no luck.

Heres where Im at so far, but if "output.txt" exists then it just deletes whats in it and doesnt create anything, but doesnt crash.

...
ofstream output;
int fileIncrement = 0;
bool validFile = false;

cout << "Saving File.." << endl;
output.open("output.txt");

while (!validFile)
{
    if (output.good()) //  does exist
    {
        fileIncrement++;
        output.open(to_string(fileIncrement) + "output.txt");
    }
    else
    {
        myVectors.outputVectors(output);
        validFile = true;
    }
}

Thank you.

Harvey
  • 1,320
  • 3
  • 13
  • 33
  • Because if the output file is opened (`good` returns true) the first condition - `if(output.good())` - is always true and `validFile` never gets set to `true`. – Captain Obvlious Apr 21 '14 at 20:12
  • It does finish though. And I thought output.open(to_string(fileIncrement + "output.txt"); would change the file opened, thus making a new one?... It does it the true and finishes, so It cant be getting stuck in the while loop – Harvey Apr 21 '14 at 20:14
  • Start up a debugger and step through the code. – Captain Obvlious Apr 21 '14 at 20:27
  • I have done. It goes through fine, This is why im so confused. I check the file afterwards, if "output.txt" is already there then it just deletes its contents but never creates a "1output.txt" like it should down to the logic – Harvey Apr 21 '14 at 20:31
  • I added output.close(); Underneeth validFile = true; Still no luck – Harvey Apr 21 '14 at 20:35
  • After even more debugging and creating a "1output.txt" it acts as if this file doesnt exist. If this helps? – Harvey Apr 21 '14 at 20:42

1 Answers1

1

output.good() just checks accessibility of the file. If it is not there yet, it will be created. Hence Captian Oblivious' comment that validFile never gets set to true. The reason the function ends is actually because you forget to close the first file before opening a second file(see here). That operation fails, setting the failbit. That's why your new file is never created, and your previous file gets overwritten.

I'm not sure of a great, standard, way to check for the (pre-)existence of a file in C++, but this sounds like what you probably want.

Community
  • 1
  • 1
user3288829
  • 1,266
  • 15
  • 26