Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

custom data iostream

I have a data structure defined as

struct myDataStruct
{
   int32_t header;
   int16_t data[8];
}

and I want to take a character stream and turn it into a myData stream. What stream class should I extend? I would like to create a custom stream class so that I can do things like

myDataStruct myData;
myDataStruct myDataArray[10];

myDataStream(ifstream("mydatafile.dat"));
myDataStream.get(myData);
myDataStream.read(myDataArray, 10);
like image 208
HazyBlueDot Avatar asked Jun 10 '26 12:06

HazyBlueDot


1 Answers

Instead of myDataStream.get(myData), what you do is overload operator>> for your data type:

std::istream& operator>>(std::istream& is, myDataStruct& obj)
{
  // read from is into obj
  return is;
}

If you want to read into an array, just write a loop:

for( std::size_t idx=0; idx<10; ++idx ) 
{
   myDataStruct tmp;
   if( is >> tmp )
     myDataArray[idx] = tmp;
   else
     throw "input stream broken!";
}

Using a function template, you should also able to overload the operator for arrays on the right-hand side (but this I have never tried):

template< std::size_t N >
std::istream& operator>>(std::istream& is, myDataStruct (&myDataArray)[N])
{
  // use loop as above, using N instead of the 10
}

But I can't decide whether this is gorgeous or despicable.

like image 107
Duncan McGregor Avatar answered Jun 12 '26 11:06

Duncan McGregor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!