0

I'm having problems when trying to write a vector of structs to a file.

void Obj::Write(wchar_t const* filename)
{
    FILE* file;
    errno_t err = _wfopen_s(&file, filename, L"wb");
    assert (file && !err);

    assert (sizeof(VertexData_VNT) == 32);
    assert (vertexArray.size() == 1654);

    //unsigned int const vertexCount = vertexArray.size();
    //if (fwrite(&vertexCount, sizeof(unsigned int), 1, file) != 1) {
    //    perror ("fwrite(&vertexCount, ...) error:");
    //}

    if (fwrite(&vertexArray, sizeof(VertexData_VNT), vertexArray.size(), file) != vertexArray.size()) {
        perror ("fwrite(&vertexArray, ...) error:");
    }

    fclose(file);
}

where vertexArray is defined as:

std::vector<VertexData_VNT> vertexArray;

and VertexData_VNT is a 32 byte struct containing only floats.

Most of the time fwrite fails with a "Invalid argument" error, and writes nothing. Though sometimes it works fine... that doesn't make sense to me.

If I uncomment the lines above I instead get an "access violation reading location" exception at the same fwrite statement. It looks to be having problems with the memcpy in fwrite.c, line 139.

Anyone have any ideas?

Gareth
  • 85
  • 1
  • 5
  • 4
    Use &vetexArray[0] or vertexArray.data(). &vertexArray is the address of the vector, not the internal array. – hmjd Jan 20 '13 at 19:25

2 Answers2

2

It should be:

&vertexArray[0]

In

if (fwrite(&vertexArray[0], sizeof(VertexData_VNT), vertexArray.size(), file) != vertexArray.size()) {
    perror ("fwrite(&vertexArray, ...) error:");
}

You are getting the address of the vector object. Not the address of the elements.

As the elements of vector are guaranteed to be in contiguous space getting the address of the first element is like the address of the front of a C-Array.

Martin York
  • 257,169
  • 86
  • 333
  • 562
2

Try &vertexArray[0] instead of &vertexArray

std::vector allocates space dynamically. The data is not located where std::vector object is, but somewhere on the heap and the vector usualy only holds a few pointers.

jrok
  • 54,456
  • 9
  • 109
  • 141