簡體   English   中英

嘗試從ifstream :: read()切換到std :: copy()

[英]Trying to switch from ifstream::read() to std::copy()

到目前為止,這是我嘗試過的方法,根本沒有填充此向量:

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

但是,以下代碼在else子句中使用read()可以正常工作:

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使用istream上的operator >>重載進行讀取; 格式化輸入,而在此示例中:

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

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

您正在讀取原始字節。 (並且您沒有填充56 short s,而是填充了56/sizeof(short) short s。)

看起來您會更喜歡istreambuf_iterator

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM