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");

}
相关推荐
CTA终结者3 小时前
期货量化环境装不上怎么办:天勤 TqSdk 安装与 Python 版本排查
开发语言·python
影寂ldy3 小时前
C# 多态与函数重载(静态多态)
开发语言·c#
SilentSamsara3 小时前
Python 与 Docker:多阶段构建、最小镜像与健康检查
运维·开发语言·python·docker·中间件·容器
变量未定义~3 小时前
快速幂、费马小定理、约数的个数、欧拉函数模板、矩阵快速幂
开发语言
hyunbar3 小时前
NOT IN 的 NULL 陷阱:一次 UNION 数据“神秘消失“
开发语言·sql
C+++Python3 小时前
如何在 Java 中使用 BIO、NIO 和 AIO?
java·开发语言·nio
basketball6163 小时前
设计模式入门:5. 代理模式详解 C++实现
c++·设计模式·代理模式
哈泽尔都3 小时前
运动控制教学——5分钟学会力控算法(阻抗/导纳/力位混合)
c++·python·算法·决策树·贪心算法·机器人·gpu算力
ZK_H3 小时前
MFC程序开发自学笔记其一——windows应用程序与c++基础
c++·笔记·mfc
189228048613 小时前
NV022固态MT29F16T08GWLCEM5-QBES:C
c语言·开发语言