示例代码如下:
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();
说输入文件包含4个MyStruct记录,字段值为1 2 3 4
输出为:101 102 102 102
而不是:101 102 103 104
为什么不寻求工作?它适用于我每次写入后刷新,但不会刷新减慢功能?
1 回答
应使用
pragma pack
将结构打包为1字节边界 . 另外,我很确定你不需要typedef
.尝试这样的事情: