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

}
相关推荐
龙俊杰的读书笔记12 分钟前
一文读懂python并发&并行编程--以xinference框架应用为例
开发语言·网络·python
liulilittle14 分钟前
递归复制搜索所有的lua文件到指定目录
java·开发语言·lua·cmd
Gofarlic_oms126 分钟前
Allegro高级功能模块许可证管理注意事项
运维·服务器·开发语言·matlab·负载均衡
启山智软29 分钟前
前沿主流技术栈商城系统(Java JDK21 + Vue3 + Uniapp)
java·开发语言·uni-app
浅念-31 分钟前
分治算法专题|LeetCode高频经典题目详细题解
数据结构·c++·算法·leetcode·职场和发展·排序·分治
H Journey37 分钟前
C++ 性能瓶颈分析与优化
c++·性能优化·gprof·perf·valgrind·瓶颈分析
QH1392923188044 分钟前
Rohde & Schwarz ZNA43矢量网络分析仪的使用方法
开发语言·php
沐知全栈开发1 小时前
SVG 实例
开发语言
geovindu1 小时前
go: Iterator Pattern
开发语言·设计模式·golang·迭代器模式
他是龙5511 小时前
70:Python安全 & SSTI模板注入 & Jinja2引擎 & 利用绕过 & 工具实战
开发语言·python·安全