因此,我要做的是创建一个结构数组。然后,我将该数组写入二进制文件。我认为寻求文件中的第二个结构并将其覆盖。然后,我将文件读回到单独的结构数组中,并将其打印到屏幕上。
写入完成后,文件大小将从24字节变为16字节,第一个结构损坏,最后一个结构从文件中丢失。
这是我的代码:
#include<fstream>
#include<iostream>
using namespace std;
struct Point
{
int x, y;
};
void print(const Point& p)
{
cout << "(" << p.x << ", " << p.y << ")" << endl;
}
int main()
{
Point p[] = {{1, 2}, {3, 4}, {5, 6}};
for(auto a : p)
print(a);
// write array p to file
fstream f("points.dat", ios::binary | ios::out);
if(f)
{
f.write(reinterpret_cast<char*>(p), 3 * sizeof(Point));
f.close();
}
// read second struct from file and print it to screen
f.open("points.dat", ios::binary | ios::in);
if(f)
{
Point p;
f.seekg( 1 * sizeof(Point), ios::beg);
f.read(reinterpret_cast<char*>(&p), sizeof(Point));
f.close();
print(p);
}
// change ios::out to ios::ate and it works fine...
f.open("points.dat", ios::binary | ios::out);
if(f)
{
Point p ={-1, -2};
f.seekp(1 * sizeof(Point), ios::beg);
// attempting to overwrite the second struct in the file
// shrinks the file from 24 bytes to 16, losing the last
// struct in the file and causing the first struct to have
// 0's in it's fields.
f.write(reinterpret_cast<char*>(&p), sizeof(Point));
f.close();
}
Point q[3];
// read the file back into q and print q for testing.
f.open("points.dat", ios::binary | ios::in);
if(f)
{
// fails because the file is now only 16 bytes, instead of 24
f.read(reinterpret_cast<char*>(q), 3 * sizeof(Point));
f.close();
for(auto a : q)
print(a);
}
}
烦人的部分是,当我将ios :: out更改为ios :: ate时,它工作得很好。
binary|out
与相同binary|out|trunc
。
即,当您使用该标志组合时,默认情况下会截断文件。
binary|out|app
。binary|out|in
。是的,我知道您没有阅读。是的,对于第二个选项,文件必须已经存在。是的,很奇怪。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句