0

I have a vector in C++ that I want to write it to a .bin file. this vector's type is byte, and the number of bytes could be huge, maybe millions. I am doing it like this:

if (depthQueue.empty())
    return;

FILE* pFiledep;

pFiledep = fopen("depth.bin", "wb");

if (pFiledep == NULL)
    return;

byte* depthbuff = (byte*) malloc(depthQueue.size() * 320 * 240 * sizeof(byte));

if(depthbuff)
{
  for(int m = 0; m < depthQueue.size(); m++)
  {
    byte b = depthQueue[m];
    depthbuff[m] = b;
  }

  fwrite(depthbuff, sizeof(byte),
        depthQueue.size() * 320 * 240 * sizeof(byte), pFiledep);
  fclose(pFiledep);
  free(depthbuff);
}

depthQueue is my vector which contains bytes and lets say its size is 100,000.
Sometimes I don't get this error, but the bin file is empty.
Sometime I get heap error.
Somtimes when I debug this, it seems that malloc doesn't allocate the space. Is the problem is with space?

Or is chunk of sequential memory is so long and it can't write in bin?

1
  • Why do you copy the vector into a buffer at all? What type is depthQueue? Commented Nov 18, 2012 at 5:55

1 Answer 1

2

You don't need hardly any of that. vector contents are guaranteed to be contiguous in memory, so you can just write from it directly:

fwrite(&depthQueue[0], sizeof (Byte), depthQueue.size(), pFiledep);

Note a possible bug in your code: if the vector is indeed vector<Byte>, then you should not be multiplying its size by 320*240.

EDIT: More fixes to the fwrite() call: The 2nd parameter already contains the sizeof (Byte) factor, so don't do that multiplication again in the 3rd parameter either (even though sizeof (Byte) is probably 1 so it doesn't matter).

Sign up to request clarification or add additional context in comments.

12 Comments

Concurrency::concurrent_vector<byte> depthQueue;
@user667222: I don't know what a Concurrency::concurrent_vector is -- you need to check its docs to see whether it provides the same contiguity guarantee. Also be consisten: is it byte or Byte?
@user667222: Given that you seem to be dealing with concurrency, if any other thread or process can write to the vector, you'll probably need to lock it before the fwrite() call and unlock it afterwards.
for now there is no concurrency issues, think of it as normal vector<>
@user667222: You can't just "think of it as normal vector" -- whether my code works depends on whether the type guarantees that all elements will be laid out contiguously in memory. It probably does, but you need to check that.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.