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

}
相关推荐
MyFreeIT19 分钟前
Python Windows Manual
开发语言·python
kiracrimson30 分钟前
STL:List的使用和模拟实现
开发语言·c++·list
二十七日秋38 分钟前
算法刷题笔记「Day 1|四道 OJ 入门题里的深坑」
c语言·汇编·数据结构·c++·笔记·python·算法
流年如夢1 小时前
继承与多态_继承篇
c++·继承·面向对象·c++进阶
北冥you鱼1 小时前
Go 语言 GORM 使用 Preload:从关联查询到嵌套预加载的完整实践
开发语言·jvm·golang
沫璃染墨1 小时前
从零入门计算机网络系列(十):HTTP协议进阶——从资源路径解析到状态码与请求头详解
linux·运维·服务器·网络·c++·http
dingzd951 小时前
TikTok账号登录态失效的Cookie字段排查路径
开发语言·php·跨境电商·营销策略
曹牧2 小时前
C#:The operation has timed out
开发语言·c#
xiaoye-duck2 小时前
《C++ 工具库实战》高性能日志 spdlog:从基础使用到工程化封装
c++·第三方库
你看我名字2 小时前
数眼智能 Search + Reader 实战:联网问答怎样避免“搜到了,却引用错了”
android·java·开发语言