Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling in std::ofstream while writing data

Tags:

c++

ofstream

I have a small program where i initialize a string and write to a file stream:

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
  std::ofstream ofs(file.c_str());
  string s="Hello how are you";
  if(ofs)
     ofs<<s;
  if(!ofs)
  {
       cout<<"Writing to file failed"<<endl;
  }
  return 0;
 }

My diskspace is very less, and the statement "ofs<" fails. So I know that this is an error logically.

The statement "if(!ofs)" does not encounter the above issue, hence I am unable to know why it failed.

Please tell me, by which other options I would be able to know that "ofs< has failed.

Thanks in advance.

like image 229
Santosh Sahu Avatar asked Feb 05 '15 11:02

Santosh Sahu


2 Answers

In principle, if there is a write error, badbit should be set. The error will only be set when the stream actually tries to write, however, so because of buffering, it may be set on a later write than when the error occurs, or even after close. And the bit is “sticky”, so once set, it will stay set.

Given the above, the usual procedure is to just verify the status of the output after close; when outputting to std::cout or std::cerr, after the final flush. Something like:

std::ofstream f(...);
//  all sorts of output (usually to the `std::ostream&` in a
//  function).
f.close();
if ( ! f ) {
    //  Error handling.  Most important, do _not_ return 0 from
    //  main, but EXIT_FAILUREl.
}

When outputting to std::cout, replace the f.close() with std::cout.flush() (and of course, if ( ! std::cout )).

AND: this is standard procedure. A program which has a return code of 0 (or EXIT_SUCCESS) when there is a write error is incorrect.

like image 185
James Kanze Avatar answered Oct 10 '22 14:10

James Kanze


I found a solution like

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
  std::ofstream ofs(file.c_str());
  string s="Hello how are you";
  if(ofs)
     ofs<<s;
  if(ofs.bad())    //bad() function will check for badbit
  {
       cout<<"Writing to file failed"<<endl;
  }
  return 0;
 }

You can also refer to the below links here and thereto check for the correctness.

like image 39
Santosh Sahu Avatar answered Oct 10 '22 15:10

Santosh Sahu