1

I found several answers on how to do it but my question is why I get a difference from using C FILE functions or using the stream read function.

If I do the following:

auto  fp = fopen( read_file.c_str(), "rb" );
fseek( fp, 0, SEEK_END );
auto  file_sz = ftell( fp );

std::vector< unsigned char > data( file_sz, 0 );

fseek( fp, 0, SEEK_SET );
fread( &data.at( 0 ), 1, file_sz, fp );
fclose( fp );

then data has 10384 values which matches file_sz.

If I do:

std::ifstream  orig_file( read_file, std::ios_base::binary );

if( orig_file.fail() )
    {
    std::cout << "Error Opening Input File [" << read_file << "]. " << strerror( errno ) << "\n";
    return;
    }

orig_file.seekg( 0, std::ios::end );
auto len = orig_file.tellg();
orig_file.seekg( 0, std::ios::beg );

std::vector< unsigned char >
                        data( len );
orig_file.read( ( char * )&data[ 0 ], len );

then data has the same 10384 bytes, but if I do the following:

std::istream_iterator< unsigned char >
                            it_begin( orig_file );
std::istream_iterator< unsigned char >
                            it_end;
std::vector< unsigned char >
                            data( it_begin, it_end );

or

data.assign( it_begin, std::istream_iterator< unsigned char >() );

data only has 10374 bytes. Thanks.

I don't understand how 9 bytes are lost when being inserted into the vector. Can you help explain that to me?

  • 2
    My guess is you have something that is being treated as white space at the end of the file. What happens if you try [this](http://stackoverflow.com/questions/17022096/input-iterator-skipping-whitespace-any-way-to-prevent-this-skipping) – NathanOliver Aug 25 '16 at 14:34
  • 2
    check out this http://en.cppreference.com/w/cpp/iterator/istream_iterator It skips whitespaces by default, to disable http://en.cppreference.com/w/cpp/io/manip/skipws – Denis Zaikin Aug 25 '16 at 14:36
  • It is indeed that whitespace was being skipped. – Grasshopper Aug 25 '16 at 16:41

0 Answers0