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

}
相关推荐
艾莉丝努力练剑13 分钟前
【AI大模型接入SDK】解决Unicode码转化以及界面变形问题
前端·c++·人工智能·学习·安全·架构
ShineWinsu1 小时前
对于Qt:事件分发器以及事件过滤器的解析
c++·qt·面试·gui·客户端·事件过滤器·事件分发器
Risehuxyc2 小时前
PHP中如何将字符串转成字节数组,再异或成一个字节
开发语言·php
饮水桶_T2 小时前
C++ STL00 | 六大核心组件协作框架 笔记
开发语言·算法·百度·facebook·新浪微博
悠仁さん3 小时前
【C++】unordered_map_set 模拟实现
开发语言·c++
Risehuxyc4 小时前
为什么php结束符?>省略不写
开发语言·php
kissskill4 小时前
MUDUO 学习笔记
c++·muduo
旖旎夜光6 小时前
【C 语言】(二)模拟实现 strlen、strcpy、strcmp、strstr、memcpy、memmove
c语言·开发语言·笔记·学习
codeejun7 小时前
每日一Go·MySQL-22、幻读、不可重复读、脏读实战演示
开发语言·mysql·golang
云草桑7 小时前
C#入坑JAVA 潜规则 API Get 多参数 Spring Boot与Spring Cloud 区别 入门系列4
java·开发语言