I save my table data in a file with a certain pattern. I will do it with x86 and read it with same pattern. It is correct.
But if a change compiler to x64 i can't read the data from file because std::string allocation size is changing.
in x86 build:
printf("string size: %d\n", sizeof(std::string)); // output is "string size: 28"
in x64 build:
printf("string size: %d\n", sizeof(std::string)); // output is "string size: 40"
When compile mode is x64, I can't read the correct data from file due to sizeof variable changing.
Is there any way to change default size of string? if i set it 28 in both compile mode. It is enought for me.
Notes
I am not using sizeof as length i use it for verify data struct
typedef struct _USER_TABLE
{
uint32_t ID;
string name;
uint16_t age;
}
DWORD dwNum;
size_t i, j, iDataTypeCount = 0;
ReadFile(hFile, &iDataTypeCount, 4, &dwNum, NULL);
std::vector<int> offsets;
if (iDataTypeCount > 0)
{
m_DataTypes.insert(m_DataTypes.begin(), iDataTypeCount, DT_NONE);
ReadFile(hFile, &(m_DataTypes[0]), sizeof(DATA_TYPE) * iDataTypeCount, &dwNum, NULL);
if (FALSE == MakeOffsetTable(offsets))
{
__ASSERT(0, "can't make offset table");
return FALSE;
}
size_t iSize = offsets[iDataTypeCount];
if (sizeof(Type) != iSize || DT_DWORD != m_DataTypes[0])
{
m_DataTypes.clear();
printf("Data Type is mismatch or size is incorrect\n");
return FALSE;
}
}
I use sizeof(_USER_TABLE) to verify and sizeof the sturct is changing depends on compile mode. Because string's size changing
There is no way to change the size of the std::string
class. Nor would changing the size of std::string
or even knowing that size be useful in storing data in a file because std::string
is not trivially copyable.
You need to do proper serialisation. One simple approach is to store the content of buffer that std::string
manages, and to rely on null terminator to determine the length of the written data.
P.S. _USER_TABLE
, __ASSERT
: These identifiers are reserved to the language implementation. You should use another name for the class, and the assertion assuming you've defined it yourself.