1,105,226 Community Members

How to check if a file exists using ofstream

Member Avatar
sarah.mathieson.7
Newbie Poster
22 posts since Sep 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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!

Member Avatar
phorce
Veteran Poster
1,005 posts since Jul 2011
Reputation Points: 105 [?]
Q&As Helped to Solve: 133 [?]
Skill Endorsements: 29 [?]
Featured
 
0
 

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
    //
    //
Member Avatar
deceptikon
Eternally Awesome
4,664 posts since Jan 2012
Reputation Points: 1,339 [?]
Q&As Helped to Solve: 679 [?]
Skill Endorsements: 104 [?]
Administrator
Featured
 
2
 

file_to_check.close();

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

Member Avatar
vmanes
Postaholic
2,132 posts since Aug 2007
Reputation Points: 1,165 [?]
Q&As Helped to Solve: 281 [?]
Skill Endorsements: 10 [?]
 
0
 

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

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: