第8题:设计一个随机读写文件程序
考虑将数据文件当作一个数组,对文件的分量进行下标访问。
可以实现一个类,重载[]能够从数据文件随机读写。
readfile.h
#ifndef READ_FILE
#define READ_FILE
#include <iostream>
#include <string>
using namespace std;
class readfile {
public:
class File {
public:
File(string& s, int n);
friend ostream& operator<<(ostream& out, File& rls);
void operator=(string add);
private:
void print(ostream& out);
string* temp;
int n;
};
readfile(string filename);
~readfile();
File& operator[] (int n);
const char operator[] (int n) const;
private:
string file;
string filename;
};
#endif
readfile.cpp
#include "randfile.h"
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
readfile::readfile(string filename) : filename(filename) {
ifstream fin;
fin.open(filename + ".txt");
while (!fin.eof()) {
string temp;
getline(fin, temp);
file += temp;
file += "\n";
}
cout << file;
fin.close();
};
readfile::~readfile() {
ofstream fout;
fout.open(filename + ".txt");
fout << file;
}
readfile::File& readfile::operator[] (int n) {
return *(new File(file, n));
}
ostream& operator<<(ostream& out, readfile::File& rls) {
rls.print(out);
return out;
}
void readfile::File::print(ostream& out) {
out << (*temp)[n];
}
void readfile::File::operator=(string add) {
if (add.length() == 1) {
(*temp)[n] = add[0];
}
(*temp).insert(n, add);
}
const char readfile::operator[] (int n) const {
return file[n];
}
readfile::File::File(string& s, int n) : n(n) {
temp = &s;
}
main.cpp
```cpp
#include <iostream>
#include "randfile.h"
using namespace std;
int main()
{
char check;
int n;
string temp;
readfile test("test");
while (1) {
cout << "1;查找指定位置的字符" << endl;
cout << "2:修改指定位置字符(当修改字符超过一个时,则直接在后面添加:" << endl;
cout << "3:退出" << endl;
cin >> check;
switch (check) {
case '1':
cout << "请输入要找字符的位置:";
cin >> n;
cout << test[n] << endl;
break;
case '2':
cout << "请输入要修改的位置:";
cin >> n;
cout << "请输入要输入的字符或者字符串";
cin >> temp;
test[n] = temp;
break;
case '3':
return 0;
break;
}
}
return 0;
}