以下示例代码:
typedef struct myStruct
{
int field;
} MyStruct;
功能:
fstream infile (filename.c_str(), ios::in | ios::out | ios::binary);
if (!infile.is_open())
{
cout << "Error: Failed to open " << filename;
return false;
}
MyStruct mystruc;
int size = sizeof(mystruc);
// get number of records in file
infile.seekg(0, ios::end);
int count = infile.tellg() / size;
infile.seekg(0,ios::beg);
for (int i = 0; i < count; ++i)
{
infile.read(reinterpret_cast<char*>(&mystruc), size);
if (infile.good())
{
mystruct.field += 100;
infile.seekp(size*-1, ios::cur);
infile.write(reinterpret_cast<char*>(&mystruc), size);
//infile.flush();
}
}
infile.close();
Say输入文件包含4个带字段值的MyStruct记录 1 2 3 4
输出是: 101 102 102 102
而不是: 101 102 103 104
为什么不寻求工作?它适用于我每次写入后刷新,但不会刷新减慢功能吗?
答案 0 :(得分:0)
您的结构应使用pragma pack
打包到1字节边界。此外,我很确定您不需要typedef
。
尝试这样的事情:
#pragma pack(push,1)
struct myStruct
{
int field;
}
#pragma pack(pop) // return to original packing