无法从结构二进制文件读取两次。我想打开并读取结构的二进制文件。代码中的注释说明。第一个循环有效,但第二个循环被完全绕过。
#include <iostream>
#include <fstream>
#include <iomanip> // this library stored the std::setw
using namespace std;
int main()
{
cout << "\n Hello world!" << endl;
struct STRUCT{
int x;
int y;
};
STRUCT myStruct;
fstream file;
file.open("c:read.dat",std::fstream::binary | std::fstream::in | std::fstream::out);
while(file.read(reinterpret_cast<char*>(&myStruct),sizeof(STRUCT))){
cout << "\n" << setw(14) << "t1" << setw(14) << "t1";// test inside loop
cout << "\n" << setw(14) << myStruct.x << setw(14) << myStruct.y ;
};
// Above will work and print
file.clear(); // **This worked. Thank you.**
file.seekg(0, ios::beg);
file.seekp(0, ios::beg);
// below printed after inserting file.clear() before file.seekg(0, ios::beg);
while(file.read(reinterpret_cast<char*>(&myStruct),sizeof(STRUCT))){
cout << "\n" << setw(14) << "q" << setw(14) << "q";// test inside loop
cout << "\n" << setw(14) << myStruct.x << setw(14) << myStruct.y ;
};
cout << "\n The End";
return 0;
}