开发者

How to close IStream?

开发者 https://www.devze.com 2023-02-14 17:14 出处:网络
How can i开发者_运维知识库 close IStream in c++?If you mean COM IStream, just call IUnknown::Release().Check this reference.

How can i开发者_运维知识库 close IStream in c++?


If you mean COM IStream, just call IUnknown::Release().


Check this reference.

// read a file into memory
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  int length;
  char * buffer;

  ifstream is;
  is.open ("test.txt", ios::binary );

  // get length of file:
  is.seekg (0, ios::end);
  length = is.tellg();
  is.seekg (0, ios::beg);

  // allocate memory:
  buffer = new char [length];

  // read data as a block:
  is.read (buffer,length);
  is.close();

  cout.write (buffer,length);

  delete[] buffer;
  return 0;
}


You can close file iostreams with ifstream::close. closing a istream doesn't really make sense - should it close the shell the program is started from?

You can flush an iostream to ensure the output is written


There are two standard subclasses of std::istream, which are closeable. If you want to close them in a context, where you only see the base class, you first need to cast to the instantiated subclass.

std::istream& is ....

// close is
std::ifstream* ifs = dynamic_cast<std::ifstream*>(&is);
if (ifs!=0)
{
    ifs->close();
}
else
{
    std::fstream* fs = dynamic_cast<std::fstream*>(&is);
    if (fs!=0)
    {
        fs->close();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消