第8题:设计一个随机读写文件程序

本文介绍了一种通过重载运算符实现文件随机读写的C++程序设计方法,该方法允许用户像操作数组一样对文件内容进行定位和修改。文章详细展示了如何创建一个自定义类来实现这一功能,并提供了完整的源代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值