I have an object that writes to a file using classic fwrite
, fseek
, and so on. It writes to files using structs, such as
fwrite(&my_struct, 1, sizeof(MyStruct_t), fd);
I did not write this code but that has been working for ~15 years. I have a requirement to convert this two objects, one that continues to write to a file in this way, and now to write to a vector to avoid the file i/o. So I replaced all fwrite
, fread
, etc, with Write
and Read
and so on. In the file writing object this simply wraps the file functions, and for the vector object this simply pushes data into the vector or moves a local vector_position
around to best maintain transparency between the two objects.
However, "writing" (and likely reading) from the vector is not working out as I hoped because of, I suppose, data alignment issues. I'm not even sure if this would be a problem in my OS (vxWorks) because I see all structs have some data alignment macro. But I would like to know if there is a non macro way to go about this.
The issue is that, I naively expected sizeof m
here to be 5
while it is actually 8
causing me to push garbage into my vector. Is there any way to do this without aligning the struct based on my compiler? I write most of my prototypes in an online environment.
#include <iostream>
#include <string>
#include <vector>
typedef struct {
uint32_t a;
char b;
} myst;
void Write(std::vector<unsigned char> &v, void *data, size_t s){
unsigned char *bdata = static_cast<unsigned char*>(data);
for(size_t i = 0; i < s; i++){
printf("0x%x\n", bdata[i]);
v.push_back(bdata[i]);
// problem - "s" = 8, not 5, so more data is written
}
}
int main()
{
myst m;
m.a = 0xA1B2C3D4;
m.b = 0xE5;
std::vector<unsigned char> s;
Write(s, &m, sizeof(m));
}