Search code examples
c++binarybinaryfilesfstream

How can I check a successful write on a binary file with c++?


I have seen these two methods to check if a written was successful on a binary file:

if (!file.write(reinterpret_cast<char*>(&variablle), sizeof(variable)))
{
    return false;
}

and

if(!file.good()) {
    cout << "Error occurred at writing time!" << endl;
    return false;
}

But, I'm not sure if this is ok, or in any case what is a good way to check that?


Solution

  • In this line:

    if (!file.write(reinterpret_cast<char*>(&variablle), sizeof(variable))) { return false; }
    

    The result of the write() method returns a reference to the stream (file). You then apply the operator ! to the file object, which returns a boolean value of true if failbit or badbit have been set on the object.

    This line:

    if(!file.good()) { cout << "Error occurred at writing time!" << endl; return false; }
    

    Calls the method good() on the object file which returns a boolean value that is immediately not-ed with !. The result of the expression is true if any of the flags failbit, badbit or eofbit are set.


    So there is a slight difference in behaviour, as the first version does not check eofbit. But effectively they are doing the same thing.


    To address some of the comments.

    This means you have successfully written to the c++ stream object. At this point it may or may not have been flushed to a physical disk as there is buffering between the write() call and disk.

    You could potentially use the flush() to make sure data has been synchronized with the output sequence.

    Most applications don't bother to go to this level of checking (but it will depend on the application).


    Summary:

    It is usually sufficient to check that write() has succeeded by using the first version.

     if (!file.write(/* Stuff */)) {
         // the write failed.
         // Do something that indicates failure.
     }
    

    If you want to inform the user about successes/failure you usually don't do that at every write operation. I would do a check at the end (when all writing has been completed).

     if (!file.good()) {
         // Tell the user something went wrong.
     }