我正在编写一个简单的 c++ 代码来读取和写入二进制文件,但我发现 ifstream 将读取记录两次。我不知道这是怎么发生的,但我尝试在 windows 和 linux 中用 mingw32 编译代码,同样的情况
ofstream outfile;
int data[5];
outfile.open("abc.out", ios::out | ios::trunc | ios::binary);
data[0] = data[1] = 1;
data[2] = data[3] = 2;
data[4] = -1;
cout << "ORIGINAL DATA:" << data[0] << " " << data[1] << " " << data[2] << " " << data[3] << " " << data[4] << endl << endl;
outfile.write((char *)&data[0], 5*sizeof(int));
outfile.close();
ifstream infile;
infile.open("abc.out", ios::in | ios::binary);
data[0] = data[1] = data[2] = data[3] = data[4] = 0;
while (!infile.eof())
{
infile.read((char *)&data[0], 5*sizeof(int));
cout << data[0] << " " << data[1] << " " << data[2] << " " << data[3] << " " << data[4] << endl;
}
这是输出
原始数据:1 1 2 2 -1
1 1 2 2 -1
1 1 2 2 -1