By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,381 Members | 1,640 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,381 IT Pros & Developers. It's quick & easy.

Reading a binary file.

P: n/a
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?
Oct 25 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Jason Heyes wrote:

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.

--
Karl Heinz Buchegger
kb******@gascad.at
Oct 25 '05 #2

P: n/a
Jason Heyes wrote:
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

Oct 25 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.