in.close();
out.close();
return0;
}
在程序运行前,先准备好输入数据文件source.txt,放入d盘的data文件夹中,内容可以如下:
231045
338920
45678883
7232-2
0-1
程序运行结束后,查看d盘的data文件夹中的结果文件target.txt内容是否正确。
返回ppt讲稿
例14.25编写一个程序对二进制文件进行读写。
本程序的功能是,从键盘输入若干学生的信息,写入二进制文件,再从该二进制文件中读出学生的信息,输出到屏幕上。
#include
#include
#include
#include
structstudent//定义一个结构体类型
{
charname[10];//姓名
charid[10];//学号
intscore;//分数
};
#defineLENsizeof(structstudent)
intmain()
{
studentst;
fstreamfile("stud.dat",ios:
:
out|ios:
:
binary);
//以二进制方式打开输出文件
if(!
file)
{
cout<<"Cannotopenoutputfile:
stud.dat"<exit
(1);
}
cin>>st.name;
while(strcmp(st.name,"#")!
=0)
//循环输入时,以输入姓名为“#”结束
{
cin>>st.id>>st.score;
//循环从键盘输入学生信息
file.write((char*)&st,LEN);
//一次写出LEN字节的内存数据
cin>>st.name;
}
file.close();
//关闭与file关联的文件,以便后面重复使用file对象
studentsts[100];
inti=0,j;
file.open("stud.dat",ios:
:
in|ios:
:
binary);
//重复使用file对象
if(!
file)
{
cout<<"Cannotopeninputfile:
stud.dat"<exit
(2);
}
while(file.read((char*)(sts+i),LEN))
//一次读入LEN字节的数据,存入内存指定地址
i++;
for(j=0;j
cout<<<'\t'<file.close();
return0;
}
程序的一次运行状况如下:
wss010180
tyy010290
czz010385
#
wss010180
tyy010290
czz010385
返回ppt讲稿
例14.26读入文本文件data.txt中的数据,
写入二进制文件data.bin中。
然后再从二进制文件中读入全部整数值,输出到屏幕上。
#include
#include
#include
usingnamespacestd;
intmain()
{
inta[100],n=0;
ifstreaminfile("data.txt");
if(!
infile)
{
cout<<"Cannotopeninputfile:
data.txt"<exit
(1);
}
while(!
infile.eof())//eof()函数的功能?
infile>>a[n++];//读入到数组中
infile.close();
ofstreamoutfile("data.bin",ios:
:
out|ios:
:
binary);
if(!
outfile)
{
cout<<"Cannotopenoutputfile:
data.dat"<exit
(2);
}
outfile.write((char*)&n,sizeof(int));//写出元素个数
outfile.write((char*)a,n*sizeof(int));//写出整个数组
outfile.close();
intb[100],m=0,i;
infile.open("data.bin",ios:
:
in|ios:
:
binary);
//重复使用infile对象
infile.read((char*)&m,sizeof(int));//读入元素个数
infile.read((char*)b,m*sizeof(int));//读入整个数组
infile.close();
for(i=0;icout<
cout<return0;
}
返回ppt讲稿