2011-12-17 2 views
1

私はMP3ファイルの最初の行を読み込もうとしています(ファイルの先頭に「私はMP3です」というテキストを含むようにこのmp3ファイルを編集しました)。fstream.read()何も読んでいない

これは私がやろうとしているものです:

#include <iostream> 
#include <string> 
#include <fstream> 
using namespace std; 

int main() 
{ 
    fstream mp3; 
    mp3.open("05 Imagine.mp3", ios::binary | ios::in | ios::out); 
    /*mp3.seekg(0, ios::end); 
    int lof = mp3.tellg(); 
    cout << "Length of file: " << lof << endl; 
    mp3.seekg(0, ios::beg);*/ 

    //char ch; 
    //cout << mp3.get(ch) << endl; 

    char* somebuf; 
    while(mp3.read(somebuf, 10)) //Read the first 10 chars which are "I'm an MP3 file". 
    { 
     //cout << somebuf; 
    } 
    return 0; 
} 

クラッシュしているいくつかの理由で、。ある時点ではクラッシュしませんでしたが、何かを印刷しても何も印刷されませんでした< < somebuf。誰かがこれで私を助けることができますか?

+0

最初の10個の文字を使用すると、11が必要なのか、なぜ – Corbin

答えて

4

あなたはsomebufのために何を割り当てられません:

char* somebuf; 

ので、それはどこにも指していません。また

char* somebuf = new char[11]; 
somebuf[10] = '\0';   // Not sure if it is necessary to null-terminate... 
while(mp3.read(somebuf, 10)) // Read the first 10 chars which are "I'm an MP3 file". 
{ 
    //cout << somebuf; 
} 


// and free it later 
delete [] somebuf; 

char somebuf[11]; 
somebuf[10] = '\0';   // Not sure if it is necessary to null-terminate... 
while(mp3.read(somebuf, 10)) // Read the first 10 chars which are "I'm an MP3 file". 
{ 
    //cout << somebuf; 
} 
+0

"私はMP3だ" でしょうか? – Kashyap

+0

それを後で削除することも忘れないでください:) また、cstring: 'char somebuf [10] = {};'を使うこともできます。文字列要素をnull文字に初期化するために '= {}'を追加しましたが、これは必須ではありませんが、一般的には良い方法です。 –

+0

@thekashyap彼はそれを印刷したい。私はそれがヌル終了する必要があるかどうかはわかりません。 – Mysticial

0

はバッファを初期化します。

char somebuf[10]; 
    while(mp3.read(somebuf, 10)) //Read the first 10 chars which are "I'm an MP3 file". 
    { 
     //cout << somebuf; 
    } 
関連する問題