C++ 解密XOR加密文件会过早中止

C++ 解密XOR加密文件会过早中止,c++,file,encryption,stl,stream,C++,File,Encryption,Stl,Stream,使用名为Encryptor struct Encryptor { char m_bKey; Encryptor(char bKey) : m_bKey(bKey) {} char operator()(char bInput) { return bInput ^ m_bKey++; } }; 我可以使用 std::ifstream input("in.plain.txt", std::ios::binary); std::ofstream out

使用名为
Encryptor

struct Encryptor {
    char m_bKey;
    Encryptor(char bKey) : m_bKey(bKey) {}
    char operator()(char bInput) {
        return bInput ^ m_bKey++;
    }
};
我可以使用

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

在本例中,该方法似乎只适用于第一个
2**12
字节,并且可能只适用于它的倍数(它可能是文件系统的块大小吗?)为什么我会有这种行为?解决方法是什么?

从您提供的源代码来看,在您尝试从磁盘读回输出流之前,输出流似乎没有关闭。由于ofstream类中有一个输出缓冲区,因此可能是您的数据仍在缓冲区中,因此未刷新到磁盘。在从磁盘读取输出流之前关闭它应该可以解决问题。

这并不能回答当前形式的问题,应该是一个注释。@RichardJ.RossIII:它不能回答问题,但Ale是完全正确的!这确实是我没有得到正确输出的原因。好吧!我会编辑一点答案,使它更清晰/清楚。显然,当我尝试复制这个时,这不会发生。@ MOOOEEEEP:谁知道微软的C++编译器“优化”相比于GCC或CLAN?如果我将介于
{/*…*/}
之间的两个en/decryption块移动到自己的作用域中,以便流将自动关闭,则我假设不会发生此错误。
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));
in.plain.txt:      7,700 bytes
out.encrypted.txt: 7,700 bytes
out.decrypted.txt: 4,096 bytes