fstream.read () вообще ничего не читает - PullRequest
1 голос
/ 17 декабря 2011

Я пытаюсь прочитать первую строку MP3-файла (я отредактировал этот mp3-файл так, чтобы в самом начале файла содержался текст «I'm MP3»).

Эточто я пытаюсь сделать:

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

По какой-то причине происходит сбой.В какой-то момент он не вылетел, но ничего не печатал, когда я делал cout << somebuf.Может кто-то помочь мне с этим?</p>

Ответы [ 2 ]

4 голосов
/ 17 декабря 2011

Вы никогда ничего не выделяли для 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 голосов
/ 17 декабря 2011

Инициализировать буфер:

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