【发布时间】:2016-12-14 13:31:00
【问题描述】:
当我在测试中使用 std::istream 对象(以下示例中来自 cplusplus.com 的 std::ifstream)时:“if (myistreamobject)”,堆栈中自动分配的对象是永远不会为空,对吗?...在下面的示例中,我们使用相同的测试来检查是否从文件中读取了所有字节...这确实是一个奇怪的代码,我通常在处理时使用这种样式用指针...
我想知道 std::istream 中使用哪种机制在测试中返回一个值,以及该值的真正含义...(最后一次操作的成功/失败??) bool cast(如 MFC 类 CString 中的 const char* 运算符)还是另一种技术?
因为对象永远不会为空,所以将其放入测试中将始终返回 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:
is.read (buffer,length);
if (is) // <== this is really odd
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;
}
【问题讨论】: