Input/output from file

Can anyone help me to tell what's wrong with this input output from binary file?

template <class T>
void RubberArray<T>::write ( ostream& fileOut )
{
fileOut.write(reinterpret_cast <const char*> (&_index), sizeof (int));
fileOut.write(reinterpret_cast <const char*> (&_len), sizeof (unsigned));
fileOut.write(reinterpret_cast <const char*> (&_size), sizeof (unsigned));
fileOut.write(reinterpret_cast <const char*> (_ra), sizeof (T)* _size);
}

template <class T>
void RubberArray<T>::read ( istream& in )
{
in.read(reinterpret_cast <char*> (&_index), sizeof (int));
in.read(reinterpret_cast <char*> (&_len), sizeof (unsigned));
in.read(reinterpret_cast <char*> (&_size), sizeof (unsigned));
in.read(reinterpret_cast <char*> (_ra), sizeof (T)* _size);
}

and in main i have:
ofstream out;
out.open ("test.txt", ios::out | ios::binary );
if (!out)
{
cout << "File Open Error" << endl;
cout << "Press Any Key To Close The Program..." << endl;
cin.get();
exit(2);
}
AR.write(out);
out.close();

RubberArray<int> Test;
ifstream in;
in.open ("test.txt", ios::in | ios::binary);
if (!in)
{
cout << "File Open Error" << endl;
cout << "Press Any Key To Close The Program..." << endl;
cin.get();
exit(2);
}
Test.read(in);
in.close();
cout << Test;
You haven;t posted all the code, but you don't seem to allocate _ra before reading into it. My guess is the code might look something like:
1
2
3
4
5
6
7
8
9
10
11
template <class T>
void RubberArray<T>::read ( istream& in )
{
    in.read(reinterpret_cast <char*> (&_index), sizeof (int));
    in.read(reinterpret_cast <char*> (&_len), sizeof (unsigned));
    in.read(reinterpret_cast <char*> (&_size), sizeof (unsigned));

    delete [] _ra;
    _ra = new t[_size];
    in.read(reinterpret_cast <char*> (_ra), sizeof (T)* _size);
}


Also, it will stand a chance of working only on built in types.

An alternative is to provide a binary stream, and write the object onto that.
Topic archived. No new replies allowed.