How do you know if a C++ fstream operation failed?

This is a discussion on How do you know if a C++ fstream operation failed? within the C++ Programming forums, part of the General Programming Boards category; say you have the following code: Code: fstream mystream; if (mystream.is_open()) { mystream << 55; mystream.close(); } How would I ...

  1. #1
    Registered User
    Join Date
    Jun 2003
    Posts
    245

    How do you know if a C++ fstream operation failed?

    say you have the following code:

    Code:
    fstream mystream;
    if (mystream.is_open())
    {
       mystream << 55;
       mystream.close();
    }
    How would I know if the "mystream << 55" actually worked and wrote the 55 to the file? The fstream part of C++ seems heavily documented in the usage of what you can do, but no ones seems interested in error handling.

  2. #2
    Registered User
    Join Date
    Jun 2002
    Posts
    230
    Salem is correct of course.
    Code:
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main()
    {
    	fstream mystream;
    
    	mystream.is_open();
    	if (mystream.fail())
    	{
    		cout << "Error opening file"<<endl;
    
    	}
    	mystream << 55;
    	mystream.close();
    	return 0;
    }
    C++ Rules!!!!
    ------------
    Microsoft Visual Studio .NET Enterprise

  3. #3
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Actually, you want to test fail() after the write command.
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  4. #4
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361
    Or just put the write operation in an if statement:
    Code:
    if (!(WriteFile << Something))
    {
         cerr << "Failed write!\n";
    }

  5. #5
    Confused
    Join Date
    Nov 2002
    Location
    Warwick, UK
    Posts
    209
    Here it is again, "cerr"... Can you explain the difference between this and "cout", and if there are any like this ?

  6. #6
    Registered User
    Join Date
    May 2003
    Posts
    148
    >>Here it is again, "cerr"
    Click.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 12-04-2008, 08:15 PM
  2. Thread Prog in C language (seg fault)
    By kumars in forum C Programming
    Replies: 22
    Last Post: 10-09-2008, 02:17 PM
  3. Replies: 16
    Last Post: 11-23-2007, 01:48 PM
  4. ARGH! fstream errors
    By OttoDestruct in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2004, 11:37 PM
  5. Problems with fstreams.
    By mosdef in forum C++ Programming
    Replies: 7
    Last Post: 06-19-2002, 04:36 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21