Chr*_*vic 5 c++ encryption stl file stream
使用一个简单的函子调用 Encryptor
struct Encryptor {
char m_bKey;
Encryptor(char bKey) : m_bKey(bKey) {}
char operator()(char bInput) {
return bInput ^ m_bKey++;
}
};
Run Code Online (Sandbox Code Playgroud)
我可以轻松地加密给定文件
std::ifstream input("in.plain.txt", std::ios::binary);
std::ofstream output("out.encrypted.txt", std::ios::binary);
std::transform(
std::istreambuf_iterator<char>(input),
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(output),
Encryptor(0x2a));
Run Code Online (Sandbox Code Playgroud)
但试图通过调用来恢复它
std::ifstream input2("out.encrypted.txt", std::ios::binary);
std::ofstream output2("out.decrypted.txt", std::ios::binary);
std::transform(
std::istreambuf_iterator<char>(input2),
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(output2),
Encryptor(0x2a));
Run Code Online (Sandbox Code Playgroud)
只做部分工作 以下是文件大小:
in.plain.txt: 7,700 bytes
out.encrypted.txt: 7,700 bytes
out.decrypted.txt: 4,096 bytes
Run Code Online (Sandbox Code Playgroud)
在这种情况下,似乎该方法仅适用于第一个2**12
字节,可能只适用于它的倍数(它可能是我的文件系统的块大小?).为什么我有这种行为以及解决方法是什么?
从您提供的源代码来看,在您尝试从磁盘读回输出流之前,输出流似乎没有关闭。由于 ofstream 类中有一个输出缓冲区,因此您的数据可能仍在缓冲区中,因此没有刷新到磁盘。从磁盘读取输出流之前关闭输出流应该可以解决问题。