Reading bytes from binary files containing '0' character

R

Rakesh Sinha

Hi,
I am writing this application in C++.
It reads data from binary files.
My current requirement is that: Given a positive number N, I have to
read in N bytes from the input stream (which is from a binary file ).

My code fragment looks as follows:

void MyStream ::readStream(char * buffer, size_t length) {
is.get( buffer, length + 1); //read length bytes from the stream
// 'is' -> field of type istream .

}

The invocation fragment looks as follows:

char * buffer = new char[length + 1];
readStream(buffer, length);


The problem occurs when the binary stream contains a null character in
it.
Suppose, if I try to read 10 characters from the stream, and the fourth
character happens to be a null character (i.e 0 ) , then only 3
characters
are read. I am looking for a work-around to read 10 characters i.e read
past this null character here. Is there any workaround to this ?
 
M

Mole Wang

The problem in your code is not caused by the stream but by the C-style string.
The "get" function does read "length" byte of data into the buffer if the input
stream doesnot meet any error or arrive at the end of file during the read operation.
When a null charactor occurs in your C-style string, it just look like to be
truncated. You just look the string to be a byte array.
 
J

Jonathan Mcdougall

Rakesh said:
Hi,
I am writing this application in C++.
It reads data from binary files.
My current requirement is that: Given a positive number N, I have to
read in N bytes from the input stream (which is from a binary file ).

My code fragment looks as follows:

void MyStream ::readStream(char * buffer, size_t length) {
is.get( buffer, length + 1); //read length bytes from the stream
// 'is' -> field of type istream .

}

The invocation fragment looks as follows:

char * buffer = new char[length + 1];
readStream(buffer, length);


The problem occurs when the binary stream contains a null character in
it.
Suppose, if I try to read 10 characters from the stream, and the fourth
character happens to be a null character (i.e 0 ) , then only 3
characters
are read. I am looking for a work-around to read 10 characters i.e read
past this null character here. Is there any workaround to this ?

Use std::istream::read().


Jonathan
 

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,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top