目录
题目
源码
结果示例
题目
建立两个二进制磁盘文件f1.dat,f2.dat,编程实现以下工作:
(1)将20个整数(可在程序中初始化),分别存放到两个磁盘文件中,前10个放到f1.dat中,后10个放到f2.dat中;
(2)从f1.dat读入10个数,然后存放到f2.dat文件原有数据后面;
(3)从f2.dat中读入20个整数,对它们按从小到大排序,结果重置f2.dat。
源码
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
int main(void)
{
int n[20] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
ofstream f1("f1.dat", ios::binary);
ofstream f2("f2.dat", ios::binary);
for (int i = 0; i < 10; i++)
{
f1.write((char *)&n[i], sizeof(int));
}
for (int i = 10; i < 20; i++)
{
f2.write((char *)&n[i], sizeof(int));
}
f1.close();
f2.close();
ifstream f1_in("f1.dat", ios::binary);
ofstream f2_out("f2.dat", ios::binary | ios::app);
int temp;
for (int i = 0; i < 10; i++)
{
f1_in.read((char *)&temp, sizeof(int));
f2_out.write((char *)&temp, sizeof(int));
}
f1_in.close();
f2_out.close();
int n2[20];
ifstream f2_in("f2.dat", ios::binary);
for (int i = 0; i < 20; i++)
{
f2_in.read((char *)&n2[i], sizeof(int));
}
ofstream f2_out2("f2.dat", ios::binary | ios::trunc);
sort(n2, n2 + 20);
for (int i = 0; i < 20; i++)
{
f2_out2.write((char *)&n2[i], sizeof(int));
}
f2_in.close();
f2_out2.close();
return 0;
}