I am looking for a way to save a vector of a struct to take up the least amount of space on file. I've read that can be accomplished with #pragma pack
(from here), and that writing can then be accomplished as follows:
#pragma pack(push,1)
struct GroupedData {
double m_average;
int m_count;
char m_identifier;
};
#pragma pack(pop)
vector<GroupedData> alldata;
//here alldata is filled with stuff
FILE *file = fopen("datastorage.bin", "wb");
fwrite(&alldata[0],sizeof(GroupedData),alldata.size(),file);
fclose(file);
However in one of the answers of that question it was said that because of memory alignment, memory access to the data would be much slower. To maintain memory efficiency and the lowest file size, I expect the following function to be able to achieve this.
struct GroupedData {
double m_average;
int m_count;
char m_identifier;
void WriteStruct(FILE* file) {
fwrite(&m_average,sizeof(double),1,file);
fwrite(&m_count,sizeof(int),1,file);
fwrite(&m_identifier,sizeof(char),1,file);
}
};
vector<GroupedData> alldata;
//here alldata is filled with stuff
FILE *file = fopen("datastorage.bin", "wb");
for (size_t i=0; i<alldata.size(); ++i)
alldata[i].WriteStruct(file);
fclose(file);
However wouldn't this write function take much longer to execute because each variable is written independently? So, how can I 'balance' fast memory access with the lowest file storage and file writing speed?