在c++ 2中读取二进制文件
Reading Binary files in C++ 2
我刚开始使用二进制文件。我试了一个简单的程序:
class student
{
int rno;
char sname[20];
public:
void input();
void output();
};
void main()
{
clrscr();
student s;
char reply;
fstream fil;
fil.open("stu.dat",ios::binary|ios::app);
do
{
s.input();
fil.write((char*)&s,sizeof(s));
cout<<"more (Y/N)n";
cin>>reply;
}
while(toupper(reply)=='Y');
fil.close();
}
void student::input()
{
cout<<"enter the rolln";
cin>>rno;
cout<<endl;
cout<<"enter the namen";
gets(sname);
cout<<endl;
}
void student::output()
{
cout<<" the rolln";
cout<<rno;
cout<<endl;
cout<<"the namen";
puts(sname);
cout<<endl;
但是当我读到这个(说我已经添加了3个学生)只有最后一个学生的详细信息显示。为什么?阅读代码:
#include<fstream.h>
#include<conio.h>
#include<stdio.h>
#include<ctype.h>
class student
{
int rno;
char sname[20];
public:
void input();
void output();
};
void main()
{
clrscr();
student s;
fstream fil;
fil.open("stu.dat",ios::binary|ios::in);
while(fil.read((char*)&s,sizeof(s)));
{
s.output();
getch();
}
fil.close();
}
void student::input()
{
cout<<"enter the rolln";
cin>>rno;
cout<<endl;
cout<<"enter the namen";
gets(sname);
cout<<endl;
}
void student::output()
{
cout<<" the rolln";
cout<<rno;
cout<<endl;
cout<<"the namen";
puts(sname);
cout<<endl;
}
但是当我读到这个(说我已经添加了3个学生)只有最后一个学生的详细信息显示。为什么?
我哪里错了?
我建议让学生自己写文件
void student::Write( fstream & fil )
{
fil.write((char*)&rno,sizeof( rno ));
fil.write((char*)&sname,20);
}
这样,如果你的类属性改变了,除了学生实现代码,你不需要重写任何东西。
相关文章:
- 正在读取二进制文件(is_open)
- 读取二进制文件并解释为整数
- 读取二进制文件直到结束 c++
- 如何在标准c ++中流式传输/读取二进制文件的中间部分并写入另一个文件?
- 读取二进制文件的惯用C++17标准方法是什么
- 从末尾读取二进制文件
- C++逐个字符读取二进制文件字符
- 读取二进制文件大小的短自上周以来停止工作
- 读取二进制文件时出现问题
- 读取二进制文件时如何输出?
- C++:如何在线程中读取二进制文件并将其写入另一个线程?
- 在C 中读取二进制文件会返回意外值
- 尝试读取二进制文件会清除文件本身
- C 读取二进制文件
- 通过C 读取二进制文件的问题
- ifstream读取二进制文件在发行模式下工作,但在调试模式下不使用
- 分段 追加和读取二进制文件时出错
- 使用C++中的MsgPack读取二进制文件
- 有没有一种优雅的方法来读取二进制文件并将其内容复制到向量<int>
- 如何读取二进制文件并在屏幕上打印 3?