从一个二进制数据文件courseFile.dat读取内容再将其输出到一个文本文件内。产生的文本文件的内容会多出一条,具体描述如下 :
二进制数据文件内容为两条记录,它们是(二进制格式无法精确表示出来):
0101 86 5
0102 72 4
但程序生成的courseFile.txt的内容第二条纪录会有重复,变成:
0101 86 5
0102 72 4
0102 72 4
显然,代码
while(!in.eof()){
in.read(reinterpret_cast<char *>(&theCourse),sizeof(course));
out<<setw(6)<<left<<theCourse.num<<setw(4)<<theCourse.hour<<setw(2)<<theCourse.credit<<endl;
}
比意想的多运行了一次out<<setw(6)......语句。 经过查资料知道,C++的read()函数刚刚读到文件尾时,eof()还是返回true.所以,while循环内的语句块多运行了一次。代码应改为:
while(1){
in.read(reinterpret_cast<char *>(&theCourse),sizeof(course));
if(!in.eof()){
out<<setw(6)<<left<<theCourse.num<<setw(4)<<theCourse.hour<<setw(2)<<theCourse.credit<<endl;
}
else
break;
}
这样就输出正确的结果了。