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<<"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;

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());
      return true;
    return false;

int main(int argc, char *argv[]) {

    string file = "file.txt";

        cout << "The file exists, sorry";

    // handle the ifstream out

Edited 3 Years Ago by phorce

This article has been dead for over six months. Start a new discussion instead.