Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c++ read binary data from istream

I have an istream and I have to read it into a buffer. I could not find a way to figure out the read_len once eof is encountered? I cannot use get because my file does not have delimeters.

It seems that the only option is to read it character by character, is it really the only option?

char buffer[128];
while(is.good()) {
     is.read(buffer, sizeof(buffer));
     size_t read_len = sizeof(buffer);
     if (is.eof()) {
         read_len = xxxx;
     }
     process(buffer, read_len);
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could check istream::gcount() which "Returns the number of characters extracted by the last unformatted input operation".

Example:

    while(is) {
         is.read(buffer, sizeof buffer);
         auto read_len = is.gcount();  // <- 
         if(read_len > 0)
             process(buffer, read_len);
         else
             break;
    }

You could also use istream::readsome() – but note:
"The behavior of this function is highly implementation-specific." which may or may not be an issue.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading