2013-07-21 50 views
5

要將我從輸入文件讀取的內容複製到向量中,我使用std::copy(),如Reading an std::ifstream to a vector of lines中推薦的那樣。將std :: ifstream讀入行向量後缺少一些字節

的問題時,如果我使用:

std::copy(std::istream_iterator<unsigned char>(inputfile), 
      std::istream_iterator<unsigned char>(), 
      std::back_inserter(myVector)); 

我的文件的第16個字節在myVector變量的缺失。

但是,如果使用下面的代碼:

inputfile.read((char*)&myVector[0], sizeof(int)*getfilesize(nameOfFile)); 

然後字節都不缺了。

我正在嘗試解析WAV文件,並在此上浪費了太多時間,我希望我能從中學到一些新東西。你能告訴我上面第一個版本的代碼有什麼問題嗎?

+1

第一個版本使用格式化的輸入函數,因此跳過了例如,它被解釋爲空白。 – dyp

+1

在這兩種情況下文件是否以二進制模式打開? –

+0

是的,除了上面我沒有改變任何東西。我使用ifstream; std :: ifstream inputfile(nameOfFile.c_str(),std :: ifstream :: in | std :: ifstream :: binary); –

回答

6

istream_iterator使用operator >>來讀取元素,但operator >>跳過空格。

您可以嘗試使用noskipws

inputfile >> noskipws; 

§ 24.6.1 P1。 (我的強調)

類模板istream_iterator是一個輸入迭代(24.2.3),該讀取(使用運算符>>)從輸入流連續 元件,用於將其構造....

+0

... iff設置了skipws標誌,它是默認設置。 – dyp

+0

至少感謝學習新事物。 –

+1

如果你想讀取二進制字節,一個更好的解決方案。可能會使用'std :: istreambuf_iterator'。 –

1

所有wav文件的第一個是二進制數據,所以你應該把它看作這樣,你應該以二進制模式打開文件:

ifstream ifs; 
ifs.open ("test.wav", ifstream::in | ifstream::binary); 

然後,你必須使用或閱讀功能按照您的說法工作。

ifstream documentation

+0

爲什麼我收到downvote? – nio

5

像RIAD說,istream_iterator執行經由operator >>格式化輸入。解決方法是在底層緩衝區上使用未格式化的讀數。爲此,請使用istreambuf_iterator

std::copy(std::istreambuf_iterator<char>(inputfile), 
      std::istreambuf_iterator<char>(), 
      std::back_inserter(myVector)); 
+1

不應該是'std :: ifstream'的'char'嗎? – dyp

+0

@DyP對,我*總是*犯這個錯誤。 –