不明白 istream::read cplusplus.com 示例

Don't understand cplusplus.com example for istream::read

本文关键字:com 示例 cplusplus read istream 明白      更新时间:2023-10-16

在 cplusplus.com 给出了一个例子:

// 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;
}

有人可以解释为什么最后一个if (is)可以确定是否读取了所有字符吗?如果我们已经进入的陈述以及我解释它的方式(可能过于简单和错误(我们只检查是否存在,这是一样的,但这不是已经建立了吗?

std::ifstream有一个转换运算符来bool,它返回是否在流上设置了badbitfailbit

它本质上是if (!is.fail()) {/*...*/}的简写。

std::ifstream定义了operator bool() const,它隐式地将流转换为布尔值。

从运算符 bool(( 的 cplusplus.com

返回是否设置了错误标志(故障位或坏位(。

请注意,此函数不返回与成员 good 相同的内容,但 成员失败的反义词。

http://www.cplusplus.com/reference/ios/ios/operator_bool/