谭浩强C++课后习题43——ASCII文件操作(2)
ASCII文件操作(1)
题目描述:建立两个磁盘文件d1.txt和d2.txt,编写程序实现以下工作:
(1)从键盘输入20个整数,分别存放在两个磁盘文件(每个文件中放10个整数)
(2)从d1.txt读入10个数,然后存放到d2.txt文件原有数据的后面。
(3)从d2.txt总读入20个整数,对他们按从小到大的顺序排序存放到d2.txt(不保留原来的数据)
#include<iostream>
#include<fstream>
using namespace std;
//fun1函数的功能是向文件中写入n个数字,文件名和n在参数中给定。
void fun1(string filename, int n) {
//定义输出流对象
ofstream outfile(filename, ios::out);
if (!outfile) {
cerr << "open error!" << endl;
exit(1);
}
//向文件中写入n个数字
int num;
for (int i = 1;i <= n;i++) {
cin >> num;
outfile << num << " ";
}
//最后关闭文件
outfile.close();
}
//fun2函数的功能是把文件1中的n个数字写入到文件2的后面。
void fun2(string filename1, string filename2, int n) {
//创建输入流对象
ifstream infile(filename1, ios::in | ios::_Nocreate);
if (!infile) {
cerr << "open error!" << endl;
exit(1);
}
//创建输出流对象
ofstream outfile(filename2, ios::app);//ios::app,写入的数据添加在文件末尾
if (!outfile) {
cerr << "open error!" << endl;
exit(1);
}
//依次循环提取第一个文件中的数字并写入第二个文件
int num;
for (int i = 1;i <= n;i++) {
infile >> num;
outfile << num << " ";
}
//最后关闭两个文件
infile.close();
outfile.close();
}
//fun3函数的功能是对该文件中的n个数字进行排序
void fun3(string filename, int n) {
//定义动态数组,长度为n
int* num = new int[n];
//定义输入流对象
ifstream infile(filename, ios::in | ios::_Nocreate);
if (!infile) {
cerr << "open error!" << endl;
exit(1);
}
//将文件中的数据提取出来存入动态数组中
for (int i = 0;i < n;i++) {
infile >> num[i];
}
//对数据进行冒泡排序
int temp;
for (int i = 0;i < n - 1;i++) {
for (int j = 0;j < n - i - 1;j++) {
if (num[j] > num[j + 1]) {
temp = num[j];
num[j] = num[j + 1];
num[j + 1] = temp;
}
}
}
infile.close();
//定义输出流对象
ofstream outfile(filename, ios::out);
if (!outfile) {
cerr << "open error!" << endl;
exit(1);
}
//再把排好序的数据重新写入到文件中
for (int i = 0;i < n;i++)
outfile << num[i] << " ";
//最后关闭文件
outfile.close();
}
int main() {
cout << "向文件1输入数据:";
fun1("d1.txt", 10);
cout << "向文件2输入数据:";
fun1("d2.txt", 10);
fun2("d1.txt", "d2.txt", 10);
fun3("d2.txt", 20);
return 0;
}
运行测试结果: