2012-12-01 49 views
-1

這是我到目前爲止已經試過,載體是沒有得到填充可言:試圖從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()填充矢量如圖第一個代碼塊?

回答

3

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