将文本文件以及二进制文件从文件中读取并显示到屏幕上
【文本文件输出】
文本文件一般以行读读数据
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
ofstream fin("e:\\chen.tex");
if(!fin)
{
cout<<"打开文件错误!"<<endl;
return 0;
}
fin<<"飞机"<<endl;
fin<<"中国"<<endl;
ifstream fout("e:\\chen.tex");
if(!fout)
{
cout<<"打开文件失败!"<<endl;
return 0;
}
string bu;
while(getline(fout,bu))//将文件中数据一行一行读取出存在bu中
{
cout<<bu<<endl;
}
fin.close();
fout.close();
system("pause");
return 0;
}
(1)第一种就是上面代码的方法,定义一个string类型来接收文件数据,并输出
(2)定义一个char类型,然后用数组表示
(3)定义一个string类型
【二进制文件输出】
以数据类型的方式组织数据
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class AA
{
private:
string name;
float score;
public:
void inputname()//相当于赋初值,可以省略构造函数
{
cin >> name;
}
void inputscore()
{
cin >> score;
}
string getname()
{
return name;
}
float getscore()
{
return score;
}
};
int main()
{
AA C[100];
string ch;
int k=0;//用来记录输入的次数,用以后面输出时的暂停
ofstream outfile("e:\\chen.dat", ios::binary );
if (!outfile)
{
cout << "无法打开文件" << endl;
}
for (int i = 0;i<100; i++)
{
cout << "请输入科目:";
C[i].inputname();
cout << "请输入成绩:";
C[i].inputscore();
outfile.write((char*)&C[i], sizeof(AA));
cout << "是否继续输入(y/n)";
cin >> ch;
if (ch == "n" || ch == "N")
{
k = i;
break;
}
}
outfile.close();
AA A2[100];
ifstream infile("e:\\chen.dat", ios::binary );
if (!infile)
{
cout << "无法打开文件" << endl;
}
for (int j = 0; j< 100; j++)
{
infile.read((char*)&A2[j], sizeof(AA));
cout << "编号:" << j + 1 << endl;
cout << "学科:" << A2[j].getname() << endl;
cout << "成绩:" << A2[j].getscore() << endl;
if (j == k)
break;
}
infile.close();
system("pause");
return 0;
}