fread equivalent with fstream
c, c++
Solution
Call the `gcount` member function directly after your call to `read`.
pf.read(&v[0],bytes);
int n = pf.gcount();
Problem
In C one can write (disregarding any checks on purpose) ``` const int bytes = 10; FILE* fp = fopen("file.bin","rb"); char* buffer = malloc(bytes); int n = fread( buffer, sizeof(char), bytes, fp ); ... ``` and `n` will contain the actual number of bytes read which could be smaller than 10 (bytes). how do you do the equivalent in C++ ? I have this but it seems suboptimal (feels so verbose and does extra I/O), is there a better way? ``` 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; } ... ```