Reading a binary file.

J

Jason Heyes

I want to read the binary contents of a file whose size is over 1 megabyte.
I tried to use this function.

bool read_file(const char *fname, std::vector<char> &data)
{
std::ifstream in(fname);
if (!in.is_open())
return false;

char block[4096];
while (in.read(block, 4096))
data.insert(data.end(), block, block + 4096);
data.insert(data.end(), block, block + in.gcount());
return true;
}

It stops after reading 4198 bytes. Can someone explain this?
 
K

Karl Heinz Buchegger

Jason said:
I want to read the binary contents of a file whose size is over 1 megabyte.
I tried to use this function.

bool read_file(const char *fname, std::vector<char> &data)
{
std::ifstream in(fname);
if (!in.is_open())
return false;

char block[4096];
while (in.read(block, 4096))
data.insert(data.end(), block, block + 4096);
data.insert(data.end(), block, block + in.gcount());
return true;
}

It stops after reading 4198 bytes. Can someone explain this?

First of all, you should open the file in binary mode.
 
M

mlimber

Jason said:
I want to read the binary contents of a file whose size is over 1 megabyte.
I tried to use this function.

bool read_file(const char *fname, std::vector<char> &data)
{
std::ifstream in(fname);
if (!in.is_open())
return false;

char block[4096];
while (in.read(block, 4096))
data.insert(data.end(), block, block + 4096);
data.insert(data.end(), block, block + in.gcount());
return true;
}

It stops after reading 4198 bytes. Can someone explain this?

Try this:

#include <iostream>
#include <fstream>
#include <vector>
#include <exception>
using namespace std;

bool read_file( const char* fname, vector<char>& data )
{
// Open in binary mode and at the end
ifstream input( fname, ios::binary | ios::ate );

// Enable exceptions on failure
input.exceptions( ios::badbit | ios::failbit );

try
{
// Get the current position in the file
const ifstream::pos_type size = input.tellg();

// Return to the beginning
input.seekg( 0, ios::beg );

// Prepare the buffer
data.resize( vector<char>::size_type(size) );

// Finally, read the data
input.read( &data[0], streamsize(size) );
}
catch( exception& e )
{
cerr << "Read failed: " << e.what() << endl;
return false;
}
return true;
}

You probably also will want to validate the conversions between
pos_type, streamsize, and size_type.

Cheers! --M
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top