Jump to content
  • Advertisement
Sign in to follow this  
ErUs

fstream binary

This topic is 4797 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

how do i read all of a binary file if i dont know its length? plz help

Share this post


Link to post
Share on other sites
Advertisement
having some problems :(

program crashing without error msg

anyone know how to read till end of file?

Share this post


Link to post
Share on other sites
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!