C++中类的封装写出一个文件加密的小项目

文件的加密较为简单,当然也可以修改它的加密方式等,供大家参考

cpp 复制代码
#include<string>
#include<fstream>
class ReaderFile
{
public:
	string Read(const string& filename)
	{
		cout << "读取文件,获取明文"<<endl;
		std::ifstream ifile;//输入流对象
		std::string src;//明文,读取内容放入src中
		char ch;
		ifile.open(filename);
		if (!ifile.is_open())
		{
			cout << "文件不存在" << endl;
			return src;
		}
		while (!ifile.eof())//fstream / ifstream / ofstream 类中的 成员函数eof()用来检测是否到达文件尾,如果到达文件尾返回非0值,否则返回0
		{
			ifile.get(ch);//读取字符
			src += ch;
		}
		ifile.close();
		return src;
	}
};
class WriterFile
{
public:
	void Write(const string& filename, const string& ciphertext)//将密文写入文件中
	{
		cout << "保存密文,写入文件" << endl;
		ofstream ofile;
		ofile.open(filename);
		if (!ofile.is_open())
		{
			cout << "文件不存在" << endl;
			return;
		}
		for (auto ch : ciphertext)//范围for
		{
			ofile.put(ch);

		}
		ofile.close();
	}
};
class Encryptor
{
public:
	string Encrypt(const string& plaintext)
	{
		cout << "数据加密,将明文转换为密文" << endl;
		std::string es;
		for (auto ch : plaintext)
		{
			char c = ch;
			if (islower(c))
			{
				c = (c + 5) % 26 + 'a';//加密方法
				es += c;
			}
		}
		return es;
	}
};
//组合
class EncryptFacade//加密器
{
private:
	ReaderFile reader;
	Encryptor encrypt;
	WriterFile writer;

public:
	EncryptFacade() {}
	void FileEncrypt(const string& des, const string& src)//把源文件加密写入目标文件
	{
		std::string s = reader.Read(src);
		if (s.empty())
		{
			cout << "加密失败!" << endl;
			return;
		}
		std::string e = encrypt.Encrypt(s);
		writer.Write(des, e);


	}
};

void main()
{
	EncryptFacade ef;
	ef.FileEncrypt("des.txt", "src.txt");

}
相关推荐
千里码aicood几秒前
[含文档+PPT+源码等]精品基于Python实现的校园小助手小程序的设计与实现
开发语言·前端·python
讨厌下雨的天空几秒前
C++之list
开发语言·c++·list
大麦大麦29 分钟前
深入剖析 Sass:从基础到进阶的 CSS 预处理器应用指南
开发语言·前端·css·面试·rust·uni-app·sass
hhw1991121 小时前
c#面试题整理6
java·开发语言·c#
Icomi_1 小时前
【神经网络】0.深度学习基础:解锁深度学习,重塑未来的智能新引擎
c语言·c++·人工智能·python·深度学习·神经网络
蠟筆小新工程師1 小时前
Deepseek可以通过多种方式帮助CAD加速工作
开发语言·python·seepdeek
不知道取啥耶2 小时前
C++ 滑动窗口
数据结构·c++·算法·leetcode
天道有情战天下3 小时前
python flask
开发语言·python·flask
zephyr_zeng3 小时前
VsCode + EIDE + OpenOCD + STM32(野火DAP) 开发环境配置
c语言·c++·vscode·stm32·单片机·嵌入式硬件·编辑器
帅弟1503 小时前
Day4 C语言与画面显示练习
c语言·开发语言