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?
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()) {/*...*/}
.