I am trying to write a program that creates a new file every time I use the application.

Right now, this is what I am doing:

outfile.open("Application.txt");
outfile<<"First Name: "<< firstName <<"     "<<"Last Name: "<< lastName<<"     "<<"Student Number: "<< studentNumber << endl;
outfile<<"Email Address: " << emailAddress <<"     "<< "Major: "
<< major << "     " <<"Year standing: "<< yearStanding << endl;
outfile<<"CGPA: "<< culmativeGPA <<"     "<<"MajorGPA: "<< majorGPA << endl;
outfile.close();

What I want to actually do, is check if application001.txt exists, and if it doesn't, create that file then write to it, and then close it. If it does exist, then I would like to write to file application002.txt or application003.txt etc...

I know I need to loop through the file names, but I don't know how to use ofstream to check if a file exists, I can only find ifstream examples.

Any help would be appreciated!

You can do this by just having a function that returns a boolean:

Something like so:

bool checkExists(string file)
{
    ifstream file_to_check (file.c_str());
    if(file_to_check.is_open())
      return true;
    return false;

    file_to_check.close();
}
int main(int argc, char *argv[]) {

    string file = "file.txt";

    if(checkExists(file))
    {
        cout << "The file exists, sorry";
        exit(0);    
    }

    // handle the ifstream out
    //
    //

file_to_check.close();

That's not necessary. If the file is open, the destructor for ifstream will close it.

And, the function will never get to the close statement in any case.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.