We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,322 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

How to check if a file exists using ofstream

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!

4
Contributors
3
Replies
15 Hours
Discussion Span
3 Months Ago
Last Updated
9
Views
sarah.mathieson.7
Newbie Poster
11 posts since Sep 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 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
    //
    //
phorce
Master Poster
738 posts since Jul 2011
Reputation Points: 63
Solved Threads: 91
Skill Endorsements: 16

file_to_check.close();

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

deceptikon
Challenge Accepted
Administrator
3,452 posts since Jan 2012
Reputation Points: 822
Solved Threads: 473
Skill Endorsements: 57

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

vmanes
Postaholic
2,015 posts since Aug 2007
Reputation Points: 1,283
Solved Threads: 242
Skill Endorsements: 6

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.1321 seconds using 2.67MB