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.

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top