为什么不能循环两次显示二进制文件中的内容?而只显示一次?解决方法
为什么不能循环两次显示二进制文件中的内容?而只显示一次?
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
struct student
{
int xueaho;
char name[20];
};
void writefile( )
{
student stu;
fstream ofs( "c:\\test.txt ", ios::out|ios::app|ios::binary);//定义fsteam对象,并打开文件
for(int i=0;i <=3;i++)
{
stu.xueaho =9801+i;
strcpy(stu.name , "wanghai ");ofs.write((char *)&stu,sizeof(student));//写文件
}
ofs.close();
}
void main()
{
writefile( );
student stu;
ifstream tfile( "c:\\test.txt ", ios::in|ios::binary);
int n=1;
do
{
tfile.seekg(0);//移动文件的内部指针
while(!tfile.eof())
{
tfile.read ((char *)&stu,sizeof(student));
cout < <stu.xueaho < <stu.name < <endl;
}
n++;
}while(n!=3);
tfile.close();
}
------解决方案--------------------
因为,你忘了清eof状态。
要加tfile.clear();
------解决方案--------------------
原来如此
------解决方案--------------------
我这里可以显示,加了tfile.clear();就显示更多
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
struct student
{
int xueaho;
char name[20];
};
void writefile( )
{
student stu;
fstream ofs( "c:\\test.txt ", ios::out|ios::app|ios::binary);//定义fsteam对象,并打开文件
for(int i=0;i <=3;i++)
{
stu.xueaho =9801+i;
strcpy(stu.name , "wanghai ");ofs.write((char *)&stu,sizeof(student));//写文件
}
ofs.close();
}
void main()
{
writefile( );
student stu;
ifstream tfile( "c:\\test.txt ", ios::in|ios::binary);
int n=1;
do
{
tfile.seekg(0);//移动文件的内部指针
while(!tfile.eof())
{
tfile.read ((char *)&stu,sizeof(student));
cout < <stu.xueaho < <stu.name < <endl;
}
n++;
}while(n!=3);
tfile.close();
}
------解决方案--------------------
因为,你忘了清eof状态。
要加tfile.clear();
------解决方案--------------------
原来如此
------解决方案--------------------
我这里可以显示,加了tfile.clear();就显示更多