fstream相当于fstream

And*_*rsK 5 c c++

在C中,人们可以写(无视任何目的的检查)

const int bytes = 10;
FILE* fp = fopen("file.bin","rb");
char* buffer = malloc(bytes);
int n = fread( buffer, sizeof(char), bytes, fp );
...
Run Code Online (Sandbox Code Playgroud)

n将包含的实际字节数读其可以是小于10(字节).

你如何在C++中做同等的事情?

我有这个,但它似乎不是最理想的(感觉如此冗长和额外的I/O),有更好的方法吗?

  const int bytes = 10;
  ifstream char> pf("file.bin",ios::binary);
  vector<char> v(bytes);

  pf.read(&v[0],bytes);
  if ( pf.fail() )
  {
    pf.clear();
    pf.seekg(0,SEEK_END);
    n = static_cast<int>(pf.tellg());
  }
  else
  {
    n = bytes;
  }

  ...
Run Code Online (Sandbox Code Playgroud)

Ben*_*ley 5

在致电gcount后直接致电会员功能read.

pf.read(&v[0],bytes);
int n = pf.gcount();
Run Code Online (Sandbox Code Playgroud)