fstream - correct error checking after output

Posted by Truncheon on Stack Overflow See other posts from Stack Overflow or by Truncheon
Published on 2010-04-09T06:55:23Z Indexed on 2010/04/09 8:23 UTC
Read the original article Hit count: 382

Filed under:
|
|
|

What's the correct way to check for a general error when sending data to an fstream?

I have the following code, which seems a bit overkill.

int Saver::output()
{
    save_file_handle.open(file_name.c_str());
    if (save_file_handle.is_open())
    {
        save_file_handle << save_str.c_str();

        if (save_file_handle.bad())
        {
            x_message("Error - failed to save file");
            return 0;
        }

        save_file_handle.close();

        if (save_file_handle.bad())
        {
            x_message("Error - failed to save file");
            return 0;
        }

        return 1;
    }
    else
    {
        x_message("Error - couldn't open save file");
        return 0;
    }
} 

© Stack Overflow or respective owner

Related posts about c++

Related posts about fstream