C++ Why is oftstream write corrupting my binary output file?

-1

I'm writing a small command line program that converts text log files into Wireshark pcapng format. I use ofstream write (opened as a binary file) to output the file. This works fine until the 12th write call. The 12th write corrupts data earlier in the file (stream).

My questions are:

  • Is my code incorrect?
  • How could I debug this?

Thanks and regards...Paul

Here are the details.

Before the 12th write, the output file looks like this:

Text

After executing the 12th write, with a data length of 0x32, the output file looks like this:

Text

Note how the file has been corrupted at offset 0x00000010, with data overwritten and random data inserted. The code looks like this:

class PcapNgFile
{
.
.
.
private:
  std::ofstream pcapng;
  size_t pcapWrite(std::vector<uint8_t> &dataOut);
.
.
.

PcapNgFile::PcapNgFile(wstring fileName, size_t ringBufferSize)
    : pcapng(fileName.c_str(), ios::binary | ios::out)
{
  if (pcapng.is_open())
  {
.
.
.

size_t PcapNgFile::pcapWrite(std::vector<uint8_t> &dataOut)
{
  size_t dataOutLength = dataOut.size();

  if (dataOutLength > 0)
  {
    // The following line of code corrupts the file on the 12th execution
    // 11 previous calls work as expected

    pcapng.write((char*)&(dataOut[0]), dataOutLength);

    // I've tried a tellp before and after this line and the put offset is correct in both cases

    dataOut.clear();
    pcapFilePosition_ += dataOutLength;
  }

  return dataOutLength;
}
c++
ofstream
asked on Stack Overflow Jan 30, 2020 by Paul Offord

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0