譚浩強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;
}
運行測試結果: