Aminos Aminos - 1 year ago 82
C++ Question

testing an istream object

When I use an std::istream object (in the example below from, an std::ifstream) in a test : "if (myistreamobject)", the object, which is automatically allocated in the stack is never null, right ?... in the example below, we are using the same test to check if all the bytes were read from the file... and that's really a strange code, I usually use that style when I'm dealing with pointers...

I want to know which mechanism is used in std::istream to return a value in tests, and what that value really means... (the success/failure of the last operation ??) is it an overloading of a bool cast (like the const char* operator cast in the MFC class CString) or it is another technique ?

Because the object is never null, so putting it in a test will always return true.

// read a file into memory
#include <iostream> // std::cout
#include <fstream> // std::ifstream

int main () {

std::ifstream is ("test.txt", std::ifstream::binary);
if (is) {
// get length of file:
is.seekg (0, is.end);
int length = is.tellg();
is.seekg (0, is.beg);

char * buffer = new char [length];

std::cout << "Reading " << length << " characters... ";
// read data as a block: (buffer,length);

if (is) // <== this is really odd
std::cout << "all characters read successfully.";
std::cout << "error: only " << is.gcount() << " could be read";

// ...buffer contains the entire file...

delete[] buffer;
return 0;

Answer Source


operator bool() 

returns true if the stream has no errors, false otherwise.

The "no error" concept is something related with the previous operation done on the stream itself.

For example: after you invoke the constructor

std::ifstream is ("test.txt", std::ifstream::binary);

A internal status flag in the stream object is set. So when you invoke the operator bool you check whether the construction operation fails or not.

Moreover the method

also set this internal status flag, as you can see in the reference:

Errors are signaled by modifying the internal state flags: eofbit, failbit, badbit.

So after the method call, if the stream reaches the EOF (end-of-file) the state bit is set, and the operator bool will return a positive value.

That means in that case when you test the stream with

if (is) { ... }

and the status bit is set, then the condition will be verified and the if-branch will be taken.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download