when use std::istream object (in example below cplusplus.com, std::ifstream) in test : "if (myistreamobject)", object, automatically allocated in stack never null, right ?... in example below, using same test check if bytes read file... , that's strange code, use style when i'm dealing pointers...
i want know mechanism used in std::istream return value in tests, , value means... (the success/failure of last operation ??) overloading of bool cast (like const char* operator cast in mfc class cstring) or technique ?
because object never null, putting in test return true.
// read file memory #include <iostream> // std::cout #include <fstream> // std::ifstream int main () { std::ifstream ("test.txt", std::ifstream::binary); if (is) { // 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 block: is.read (buffer,length); if (is) // <== odd std::cout << "all characters read successfully."; else std::cout << "error: " << is.gcount() << " read"; is.close(); // ...buffer contains entire file... delete[] buffer; } return 0; }
the
operator bool()
returns true if stream has no errors, false otherwise.
the "no error" concept related previous operation done on stream itself.
for example: after invoke constructor
std::ifstream ("test.txt", std::ifstream::binary);
a internal status flag in stream object set. when invoke operator bool check whether construction operation fails or not.
moreover method
is.read(...)
also set internal status flag, can see in reference:
errors signaled modifying internal state flags: eofbit, failbit, badbit.
so after method call, if stream reaches eof (end-of-file) state bit set, , operator bool return positive value.
that means in case when test stream with
if (is) { ... }
and status bit set, condition verified , if-branch taken.
Comments
Post a Comment