试图从ifstream的读取::()到std ::复制开关()

问题描述:

这是我到目前为止已经试过,载体是没有得到填充可言:试图从ifstream的读取::()到std ::复制开关()

#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; 
} 

但是下面的代码只是正常使用read()else子句中:

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, " ") 
      ); 

有我丢失的东西让std::copy()填充矢量如图第一个代码块?

istream_iterator使用operator >>读数的读数istream;这不格式化输入,而在这个例子中:

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

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

你正在阅读的原始字节。 (和你不填充56个short S,你是填充56/sizeof(short)short秒)

它看起来像你会与istreambuf_iterator快乐。

+0

http://stackoverflow.com/questions/13665534/getting-desired-binary-data-ranges-from-stdistreambuf-iterator-and-stdifstre相关的问题,如果你想拍摄它。 – Tek