Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fread equivalent with fstream

Tags:

c++

c

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

  ...
like image 807
AndersK Avatar asked Nov 21 '12 06:11

AndersK


3 Answers

Call the gcount member function directly after your call to read.

pf.read(&v[0],bytes);
int n = pf.gcount();
like image 72
Benjamin Lindley Avatar answered Oct 04 '22 23:10

Benjamin Lindley


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

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

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

If the End-of-File is reached before n characters have been read, the array will contain all the elements read until it, and the failbit and eofbit will be set (which can be checked with members fail and eof respectively).

Notice that this is an unformatted input function and what is extracted is not stored as a c-string format, therefore no ending null-character is appended at the end of the character sequence.

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

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

like image 24
Jonathan Leffler Avatar answered Oct 05 '22 00:10

Jonathan Leffler


pf.read(&v[0],bytes);

streamsize bytesread =  pf.gcount();
like image 30
Duck Avatar answered Oct 05 '22 01:10

Duck