如何用c++设计一个代码,代码不少于1000行,标注释,内容为投资理财信息管理系统?
思路:
先将源文件数据copy一份到目标文件,然后在目标文件中进行数据的排序。
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
//写随机数到源文件,保证源文件存在并且存在数据。
void rand_write() {
cout << "This is from rand_write"<<endl;
ofstream in_file("d:\\f1.txt", ios::out);
srand((int)time(0));
A:
int n = rand() % (20-5)+5;
if (n == 0) goto A;
cout << "num:" << n << endl;
for (int i = 0; i < n; i++)
{
int temp = rand() % 100;
in_file.write((char*)(&temp), sizeof(int));
cout << temp << " ";
}
cout << endl;
in_file.close();
}
int main() {
rand_write();
ifstream in_file("d:\\f1.txt", ios::binary | ios::in);
fstream out_2("d:\\f2.txt", ios::binary | ios::out|ios::in|ios::trunc);//此处的ios::trunc应该保留,确保多次运行不会造成目标文件中无用数据堆积。
if (!in_file ) {
cerr << "open error!" << endl;
return -1;
}
if (!out_2) {
return -1;
}
int temp;
int n=0;
cout << "copy to f1.txt:" << endl;
while (in_file.read((char*)&temp, sizeof(int))) {
out_2.write((char*)&temp, sizeof(int));
cout << temp << " ";
n++;
}
cout << endl;
in_file.close();
out_2.close();
out_2.open("d:\\f2.txt", ios::binary | ios::in | ios::out);//此处没有ios::trunc是为了对目标文件中的数据进行排序,所以不能将其截断。
if (!out_2) {
cerr << "open error!" << endl;
return -2;
}
//以下是对目标文件数据的排序操作,参考冒泡排序法写的。
cout << "The process of sort:" << endl;
for (int i=0;i<n;i++)
{
int temp_i;
int temp_j;
int find_min_key=i;
int temp_min;
out_2.seekg((i*sizeof(int)), ios::beg);
out_2.read((char*)&temp_i, sizeof(int));
temp_min = temp_i;
for (int j=i+1;j<n;j++)
{
out_2.read((char*)&temp_j, sizeof(int));
if (temp_j < temp_min) {
find_min_key = j;
out_2.seekg(find_min_key * sizeof(int));
out_2.read((char*)&temp_min, sizeof(int));
}
}
if (find_min_key != i) {
out_2.seekp(i * sizeof(int), ios::beg);
out_2.write((char*)&temp_min, sizeof(int));
out_2.seekp(find_min_key * sizeof(int), ios::beg);
out_2.write((char*)&temp_i, sizeof(int));
}
out_2.seekg(0);
cout << "sort:" << i + 1 << endl;
for (int i = 0; i < n; i++)
{
out_2.read((char*)&temp, sizeof(int));
cout << temp << " ";
}
cout << endl;
}
out_2.clear();
out_2.seekp(0,ios::beg);
cout << endl << "After sort";
cout << "(num:" << n <<"):"<< endl;
for (int i = 0; i < n; i++)
{
out_2.read((char*)&temp, sizeof(int));
cout << temp << " ";
}
cout << endl;
out_2.close();
}
记录一下遇到的坑:
在read,write方法中第二个参数写成sizeof(int)和sizeof(temp)造成的效果可能是不一样的。(目前不确定比较迷惑)
对文件的读写操作完成后进行下一次读写的时候要记得修改文件指针的位置。
经常出现写入冲突:
可能是文件在打开之后忘了关闭,切记自己写的函数中在函数结束前关闭文件。
还有一种可能是读入的数据大小超过了保存该数据的变量的内存大小。即造成内存溢出。
内存这块的错误真是块难啃的骨头。