ifstream binary read into unsigned char b[LENGTH]

S

Steven T. Hatton

What is the best way to read data from a file into a fixed size array of
unsigned char? This is a file holding only a SHA1 digest. What I would
really like to do is initialize the ifstream with the buffer allocated to
hold the data, seekg(ios_base::end) and magically have the data appear in
the buffer. I believe something close to this can be done.

I might allocate the array:

const unsigned LENGTH = 256;
unsigned char b[LENGTH];

Then cast it to a std::streambuf

std::streambuf sb(b[LENGTH]);

But can I construct std::ifstream that uses that same memory to hold the
data from its file? How to I prevent reading past the end of my buffer, or
the end of the file data?
 
R

Rolf Magnus

Steven said:
What is the best way to read data from a file into a fixed size array of
unsigned char? This is a file holding only a SHA1 digest. What I would
really like to do is initialize the ifstream with the buffer allocated to
hold the data, seekg(ios_base::end) and magically have the data appear in
the buffer.

Why should a seek read any data?
I believe something close to this can be done.

I might allocate the array:

const unsigned LENGTH = 256;
unsigned char b[LENGTH];

Then cast it to a std::streambuf

std::streambuf sb(b[LENGTH]);

I don't think that you can be sure that the buffer will contain exactly the
data you want. After all, it's a buffer that's meant for internal use.
But can I construct std::ifstream that uses that same memory to hold the
data from its file?

The purpose of streams is text formatting. If you want to read binary data,
just use a filebuf directly.
How to I prevent reading past the end of my buffer, or the end of the file
data?

Your idea seems overly complicated to me. Just use the filebuf::sgetn()
function to read as many bytes as you want and you're done.
 
S

Steven T. Hatton

Rolf said:
Why should a seek read any data?

As I understand things, that will (usually?) force the file to be completely
read into memory.
Your idea seems overly complicated to me. Just use the filebuf::sgetn()
function to read as many bytes as you want and you're done.

Will that copy the bytes from one location in memory to another? That's
what I want to avoid. This is basically the same thing as move semantics.
Rather than copying the contents of the buffer, I simply want to take
ownership of it.
 

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

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,278
Latest member
BuzzDefenderpro

Latest Threads

Top