Sign in to follow this  
ErUs

fstream binary

Recommended Posts

When reading so called "binary" files with streams you want to use unformatted I/O operations, two possible choices:

1.

#include <iterator>
#include <vector>
#include <fstream>

int main() {

std::ifstream in("foo", std::ios_base::binary);

std::vector<char> v((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
}


or

2.

#include <vector>
#include <fstream>

int main() {

std::ifstream in("foo", std::ios_base::binary);

in.seekg(0, std::ios_base::end);
const std::streamsize length = in.tellg();
in.seekg(0, std::ios_base::beg);

std::vector<char> v(length);
in.read(&v[0], length);
}


The latter will most likely be slightly faster, due to the fact of using an explicit block I/O operation.

Make sure you check the state of a stream after an I/O op or turn on stream exceptions and do exception handling instead if you wish.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this