习题 13.4 建立两个磁盘文件f1.dat和f2.dat,编程序实现以下工作:
(1) 从键盘输入20个整数,分别存放在两个磁盘文件中(每个文件中放10个整数);
(2) 从f1.dat读入10个数,然后存放到f2.dat文件原有数据的后面;
(3) 从f2.dat中读入20个整数,将它们按从小到大的顺序存放到f2.dat(不保留原来的数据)。
分部完成:
(1) 从键盘输入20个整数,分别存放在两个磁盘文件中(每个文件中放10个整数)
代码:
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
void func_1(int *,const int); //实现第一个任务
const int N = 20;
int a[N];
cout << "请输入20个整数:" << endl;
for (int i = 0; i != N; ++i)
{
cin >> a[i];
}
func_1(a,N);
return 0;
}
void func_1(int *a,const int n)
{
int i;
ofstream outfile("f1.dat", ios::out); //建立连接
if (!outfile)
{
cerr << "f1 open error!" << endl;
exit(1);
}
for (i = 0; i != 10; ++i) //写入文件
{
outfile << a[i] <<" ";
}
outfile.close(); //关闭连接f1的流
outfile.open("f2.dat", ios::out); //建立连接f2的流
if (!outfile)
{
cerr << "f2 open error!" << endl;
exit(1);
}
for (; i != n; ++i)
{
outfile << a[i] <<" ";
}
outfile.close()