Andy Ibanez
Andy Ibanez

Reputation: 12254

fstream.read() Not Reading Anything At All

I'm trying to read the first line of an MP3 file (I edited this mp3 file to contain the text "I'm an MP3" right at the beginning of the file).

This is what I'm trying to do:

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

For some reason, that is crashing. At some point it didn't crash, but it didn't print anything when I did cout << somebuf. Can someone help me with this?

Upvotes: 1

Views: 1574

Answers (2)

Kashyap
Kashyap

Reputation: 17411

Initialize the buffer:

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

Upvotes: 0

Mysticial
Mysticial

Reputation: 471209

You never allocated anything for somebuf:

char* somebuf;

therefore, it doesn't point anywhere.

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;

Alternatively:

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

Upvotes: 4

Related Questions