Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using the "!" operator during file input/output operations in C++

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading