Tek
Tek

Reputation: 3050

How to fread into a vector inside a class?

class WavFile
{
    std::vector<short> SoundData;

public:

    std::vector<short> getSoundData()
    {
        return SoundData;
    }
}

Normally I'd use fread( &SoundData[0], 1, 1337, SomeFile );

But now that I'm using a vector inside a class, I'm having trouble with the following:

Upvotes: 1

Views: 1491

Answers (3)

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39380

What you are trying to do is bad in general. There are some main points to it:

If you are encapsulating vector in class, you can still operate on it normally from the outside if it's public.

WavFile WF;
void* Ptr = WF.SoundData.data();
// void* Ptr = &WF.SoundData[0]; - C++03

You can also wrap some of the calls to the vector, .resize() for example:

void WavFile::resize(vector::size_type new_size) {
    SoundData.resize(new_size);
}

void* WavFile::getRawPtr () {
    return SoundData.data();
    // return (&SoundData[0]); - C++03
}

If you are using std::vector, you should also use corresponding C++ read functions on it. Treating vector as a memory array is valid, but there are better ways to use it, fstream for example.

If you are encapsulating vector (or any std container in general), don't return it by value! It will cause all of the elements to be copied. Instead, return a const-reference to container, or, even better, range.

Upvotes: 2

TieDad
TieDad

Reputation: 9899

You cannot use vector as argument to fread. You have to allocate a block of memory (short buffer[SIZE]) as buffer to read data in, then insert data element by element to vector from the buffer.

Although fread is allowed in C++, it's better to use native C++ way to read file, such as fstream.

Upvotes: 0

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361452

  • Knowing how to set the vector size outside the class.

You can construct the vector passing the size to the vector's constructor.

  • And I'm not sure how to use the method as an argument for fread to put the data inside the vector.

Why are you using fread to begin with? Why not fstream?

Also, once you initialize the vector passing the size, you can use &v[0] just as you would use if it was declared as c-array (i.e float v[const_size]).

Upvotes: 1

Related Questions