Thread: std::ifstream question

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    12

    std::ifstream question

    I would like to respond to a failure of not being able to open a file by trying to open a different file, but it seems like if you fail once you're going to fail again even if you try to open a file that is really there:

    Code:
    std::ifstream f;
    	f.open(filename.c_str());
    
    	if(f.fail())
    	{
    		// do something appropriate
    		f.close();
    		f.open("data\\setpieces\\24x24_1_0_0.txt");
    	}
    
    // f will fail again even though the file I'm trying to open is really there
    Is there some way of revalidating the f object?

  2. #2
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    f.clear()

    The stream object has error flags that get set when there is a problem. They stay set until you clear() them.

  3. #3
    Registered User
    Join Date
    Mar 2006
    Posts
    12
    wow what a fast responce. I'll have to come here more often. Thanks.

  4. #4
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    Quote Originally Posted by psyadam
    Is there some way of revalidating the f object?
    Since you understand the logic of it being an object, you might also understand that the failed state is simply a Boolean member that's been flagged false. Calling the close() method doesn't flip that flag back.
    Sent from my iPadŽ

  5. #5
    Registered User
    Join Date
    Mar 2006
    Posts
    12
    f.clear() did the trick. Thanks, i didn't see that function documented on msdn.microsoft.com

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Debugging question
    By o_0 in forum C Programming
    Replies: 9
    Last Post: 10-10-2004, 05:51 PM
  2. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 12:52 PM
  3. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  4. Question about linked lists.
    By cheeisme123 in forum C++ Programming
    Replies: 6
    Last Post: 02-25-2003, 01:36 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 01:47 AM