输入输出流
zhu:cheng se bu fen shi cheng xu de guan jian bu fen !!!
对ASCII文件的操作
1 写数据进入磁盘文件
eg: 从键盘中输入10个数存入数组,输入进磁盘文件
#include <fstream>//因为要进行对文件的写操作
#include <iostream>
using namespace std;
int main()
{
ofstream out;//建立输出流对象
out.open("l.text",ios::out) ;//以写的方式打开文件
if(!out)//判断文件是否打开成功
{
cerr<<"打开文件失败" <<endl;
exit(1);//停止程序
}
int a[10] ;
for(int i=0;i<10;i++)
{
cin>>a[i];//键盘输入给数组
}
for(int i=0;i<10;i++)
{
out<<a[i]<<" ";//使用定义的流对象,将数据从键盘输出到磁盘文件从存放
}
out.close() ;//文件关闭;
return 0;
}
(2)从文件中读取数据
eg:从上个题中的文件读取10个数的数据并找出最大值和它所在的数组的序号
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream infile;//建立输入流对象
infile.open("l.text",ios::in);//以输入的方式打开文件
if(!infile)
{
cerr<<"打开失败";
exit(1);//停止程序
}
int a[10];
int max=0,n;//分别为最大值和数组下标
for(int i=0;i<10;i++)
{
infile>>a[i] ;//从文件中读入10个数字存放进数组
}
for(int i=0;i<10;i++)
{
if(max<a[i])
{
max=a[i];
n=i;
}
}
cout<<"最大值" <<max<<endl;
cout<<"最大值下标" <<n<<endl;
infile.close();//文件关闭
return 0;
}
(3), (1)(2)的结合
(1)从键盘输入数据进入文件,(2)是从文件提取数据然后再存放进另一个磁盘文件
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outfile;//建立输出流对象
outfile.open("y.text",ios::out) ;//以写的方式打开文件
if(!outfile) //判断
{
cerr<<"打开错误"<<endl;
exit(1) ;//程序停止
}
char a[10] ;
cin.getline(a,10);//获取一行数据
for(int i=0;i<10;i++)
{
if(a[i]>=65&&a[i]<=90||a[i]>=97||a[i]<=122)//如果是字母字符
{
outfile<<a[i] <<endl;//放入磁盘文件
cout<<a[i] <<endl;//显示器显示,便于读者观看
}
}
outfile.close();//文件关闭
//前面的操作和(1)其实差不多 ,从键盘输入数据进入磁盘
char ch;
ifstream infile;//定义输入流对象
infile.open("y.text",ios::in);//打开刚才存放的数据文件
if(!infile)
{
cerr<<"打开错误"<<endl;
exit(1) ;//程序关闭
}
ofstream outfile1;
outfile1.open("l.text",ios::out);
if(!outfile1)
{
cerr<<"打开错误"<<endl;
exit(1) ;//程序关闭
}
while(infile.get(ch))
{
if(ch>=97&&ch<=122)
ch=ch-32;//大小写转换
outfile1.put(ch);//存入另一个磁盘文件
cout<<ch;//显示
}
infile.close();
outfile1.close(); //关闭文件
return 0;
}
对二进制文件的操作
(4)将二进制文件中的数据存放进磁盘文件
#include <iostream>
#include <fstream>
using namespace std;
struct student
{
int n;
int age;
char sex;
};
int main()
{
student stu[3]={1,12,'f',2,13,'m',3,14,'m'};
ofstream out;
out.open("l.text",ios::binary);
if(!out)
{
cerr<<"错误"<<endl;
abort() ;
}
for(int i=0;i<3;i++)
{
out.write((char*)&stu[i],sizeof(stu[i]));//起始指针和长度
}
out.close();
return 0;
}
(5)将二进制文件数据从磁盘中读入内存并显示
#include <iostream>
#include <fstream>
using namespace std;
struct student
{
int n;
int age;
char sex;
};
int main()
{
student stu[3];
ifstream infile;
infile.open("l.text",ios::binary);
if(!infile)
{
cerr<<"error"<<endl;
abort();
}
int i;
infile.read((char*)&stu[i],sizeof(stu[i]));
infile.close();
for(int i=0;i<3;i++)
{
cout<<"n"<<stu[i].n<<endl;
cout<<"age"<<stu[i].age<<endl;
cout<<"sex"<<stu[i].sex<<endl;
cout<<endl;
}
return 0;
}