Reputation: 105
On cplusplus.com an example is given:
// 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:
is.read (buffer,length);
if (is)
std::cout << "all characters read successfully.";
else
std::cout << "error: only " << is.gcount() << " could be read";
is.close();
// ...buffer contains the entire file...
delete[] buffer;
}
return 0;
}
Can someone please explain why the last if (is)
can determine if all characters have been read? It's the same if statement we're already in and the way I interpreted it (probably too simplistically and false at that) we only check if is exists, but wasn't this already established?
Upvotes: 2
Views: 198
Reputation: 65630
std::ifstream
has a conversion operator to bool
, which returns whether or not badbit
or failbit
is set on the stream.
It is essentially shorthand for if (!is.fail()) {/*...*/}
.
Upvotes: 3
Reputation: 4232
std::ifstream
defines operator bool() const
, which implicitly converts the stream to a boolean.
From cplusplus.com on operator bool():
Returns whether an error flag is set (either failbit or badbit).
Notice that this function does not return the same as member good, but the opposite of member fail.
http://www.cplusplus.com/reference/ios/ios/operator_bool/
Upvotes: 1