示例代码如下:
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
为什么 seekp 不起作用?它可以在每次写入后刷新,但刷新不会减慢功能吗?
最佳答案
您的结构应该使用 pragma pack
打包到 1 字节边界。另外,我很确定您不需要 typedef
。
尝试这样的事情:
#pragma pack(push,1)
struct myStruct
{
int field;
}
#pragma pack(pop) // return to original packing
关于用于读写的 C++ 二进制 fstream 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8332092/