fstream.read()根本不读任何东西

时间:2011-12-17 04:09:52

标签: c++ binaryfiles fstream

我正在尝试阅读MP3文件的第一行(我编辑了这个mp3文件,以便在文件开头包含文本“我是一个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时它没有打印任何东西&lt;&lt; somebuf。有人可以帮我弄这个吗?

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

初始化缓冲区:

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