-1

This is what I've tried so far, the vector is not getting populated at all:

#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>

int main()
{
    std::ifstream file("E:\\test3.wav", std::ios::binary );

    if( file.fail() )
    {
        std::cout << "File does not exist or could not open file";
    }
    else
    {
        std::vector<short> buffer;

        //read
        std::copy(
                    std::istream_iterator<short>( file ),
                    std::istream_iterator<short>(),
                    std::back_inserter( buffer )
                    );

        //size outputs to 0
        std::cout << buffer.size();
    }

    return 0;
}

However the following code works just fine using read() inside the else clause:

std::vector<short> buffer( 56 );

    //read
    file.read( (char *) &buffer[0], 56 );

    //outputs the whole file with all expected values showing.
    std::copy( 
                 buffer.begin(), 
                 buffer.end(), 
                 std::ostream_iterator< short >( std::cout, " " )
             );

Is there something I'm missing to get std::copy() to populate the vector as shown in the first block of code?

Tek
  • 2,888
  • 5
  • 45
  • 73

1 Answers1

3

istream_iterator reads using operator >> overloads on istream; which do formatted input, whereas in this example:

std::vector<short> buffer( 56 );

//read
file.read( (char *) &buffer[0], 56 );

you are reading raw bytes. (and you are not populating 56 shorts, you are populating 56/sizeof(short) shorts.)

It looks like you'd be happier with an istreambuf_iterator.

Billy ONeal
  • 104,103
  • 58
  • 317
  • 552
  • http://stackoverflow.com/questions/13665534/getting-desired-binary-data-ranges-from-stdistreambuf-iterator-and-stdifstre Related question, if you want to take a shot at it. – Tek Dec 02 '12 at 02:34