Equivalent to fread with fstream

You can write in C (without taking into account any checks)

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 may be less than 10 (bytes).

how do you execute 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; } ... 
+4
source share
3 answers

Call the gcount function immediately after your read call.

 pf.read(&v[0],bytes); int n = pf.gcount(); 
+5
source

According to http://www.cplusplus.com/reference/iostream/istream/read/ :

istream& read(char* s, streamsize n);

Read data block
Reads a data block of n characters and stores it in the array specified by s.

If the final file is reached before n characters are read, the array will contain all the elements read before it, and the failbit and eofbit parameters will be set (which can be checked with member error and, respectively,).

Note that this is an unformatted input function, and what is extracted is not saved as a c-string format, so no trailing null character is added at the end of a sequence of characters.

Calling the gcount member after this function can get the total number of characters read.

So pf.gcount() tells you how many bytes have been read.

+2
source
 pf.read(&v[0],bytes); streamsize bytesread = pf.gcount(); 
+1
source

Source: https://habr.com/ru/post/1447409/


All Articles