Thread: Reading blocks of binary data into a vector<unsigned char>?

  1. #1
    Registered User
    Join Date
    Mar 2010
    Location
    China
    Posts
    74

    Reading blocks of binary data into a vector<unsigned char>?

    Instead of
    Code:
    while(vec.size() < 65536 && (ch = stream.get(), !stream.eof()))
        vec.push_back(ch);
    Is there any elegant way of doing that?

  2. #2
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Instead of reading one character at a time, read BUFF_SIZE characters at a time.

    You can also directly query the stream buffer:
    Code:
    streambuf * pbuf = stream.rdbuf();
    streamsize sizeOfBuffer= pbuf->in_avail()!=0? pbuf->in_avail(): BUFF_SIZE;
    /*in_avail gets the expected number of characters available after an underflow, or number of characters in buffer.*/
    In either case you use the value to determine how many characters to read in each loop iteration.
    Last edited by King Mir; 08-14-2011 at 02:33 AM.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  3. #3
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    It is possible to use stream iterators.
    I don't remember the exact syntax, but that might help you on the way:

    std::copy(std::istream_iterator(stream), std::istream_iterator(), std::back_inserter(vec));
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 11
    Last Post: 06-16-2011, 11:59 AM
  2. Replies: 2
    Last Post: 10-06-2009, 09:37 AM
  3. Replies: 9
    Last Post: 04-04-2008, 12:41 PM
  4. Replies: 2
    Last Post: 02-20-2005, 01:48 PM
  5. How to change data format between unsigned char and CString?
    By ooosawaddee3 in forum C++ Programming
    Replies: 1
    Last Post: 11-07-2002, 02:49 PM