5

と呼ばれる単純なファンクターを使用する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));

ただし、呼び出してこれを元に戻そうとします

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

この場合、メソッドは最初の2**12バイトに対してのみ機能し、おそらくその倍数に対してのみ機能するようです (ファイルシステムのブロックサイズでしょうか?)。この動作が発生するのはなぜですか? また、その回避策は何ですか?

4

1 に答える 1

4

あなたが与えたソースコードから、ディスクから読み戻そうとする前に出力ストリームが閉じられていないようです。ofstream クラスに出力バッファがあるため、データがまだバッファ内にあり、ディスクにフラッシュされていない可能性があります。ディスクから読み取る前に出力ストリームを閉じると、問題が解決するはずです。

于 2013-03-27T20:10:16.173 に答える