Home > OS >  Using the "!" operator during file input/output operations in C
Using the "!" operator during file input/output operations in C

Time:02-06

I'm reviewing a project that does file input/output operations in C . There are uses for the overloaded ! operator defined in std::ios that I have not encountered before. I know that the ! operator is used to check if a file has been opened. However, I did not understand why the author used the fstream object by using the ! operator after using the istream::seekg, istream::read, ostream::seekp, ostream::write methods in the project I was examining.

Below is a part of the add() function in the source code I've reviewed:

#include <fstream>
#include <iostream>

bool add(std::fstream &file, std::istream &input)
{
    file.seekg((id - 1) * sizeof(Person));
    /* What is the purpose of using the "operator!" below? */
    if(!file){ return false; }

    file.read(reinterpret_cast<char *>(&temp), sizeof(Person));
    /* What is the purpose of using the "operator!" below? */
    if(!file){ return false; }

    file.seekp((id - 1) * sizeof(Person));
    /* What is the purpose of using the "operator!" below? */
    if(!file){ return false; }

    file.write(reinterpret_cast<const char*>(&person), sizeof(Person));
    /* What is the purpose of using the "operator!" below? */
    if(!file){ return false; }
}

Do the above uses of the operator! operator make any sense?

CodePudding user response:

The ! operator is overloaded for classes derived from std::basic_ios (such as std::fstream) to indicate whether or not an error has occurred following an operation, or that has not been cleared after an earlier operation.

From cppreference:

Returns true if an error has occurred on the associated stream. Specifically, returns true if badbit or failbit is set in rdstate().

In the code sample you have shown, the ! operator is called after every attempted operation on the stream and, if an error is detected, the function aborts and returns a false signal. (Note that any of those seek/read/write operations could potentially fail.)

So:

Do the above uses of the operator! operator make any sense?

Yes, they do. That's good, exemplary code, which should be commended in any review.

  •  Tags:  
  • Related