Question

The following question had been asked probably, but I couldn't find it.

I have create a class BinaryWriter.
I need to implement the following method:

  /// Write zero bytes to file
  virtual void wr_padding( int padding_size); 

I have the following implementation:

void BinaryWriter::wr_padding( int padding_size)
{
  char pad_arr[padding_size];
  memset(pad_arr, 0, padding_size);
  m_stream.write(pad_arr,padding_size);
}

where:

   std::ostream m_stream; 

I'm not to happy with this implementation. I was hoping to have an ios API for this simple task. Is there more native implementation?

Thanks

Was it helpful?

Solution

First, your code isn't valid; the size of a C style array must be a constant. A valid version would be:

void
BinaryWriter::wr_padding( int padding_size)
{
  std::vector<char> pad_arr( padding_size );
  m_stream.write( &pad_arr[0], pad_arr.size() );
}

However: can you set some maximum value for padding_size? (In XDR, for example, it will never be more than 4.) If so, something as simple as:

void
BinaryWriter::wr_padding( int padding_size )
{
    static char const pad_arr[ max_padding_size ] = {};
    m_stream.write( pad_arr, padding_size );
}

would do the trick.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top