rc4の実装を記述しようとしています。私はifstreamを使ってファイルから平文を読み込んでいます。私はそれがファイルの最後に出力されていないことに気付いたので、バッファを明示的にクリアするさまざまな方法を試しました。どのような方法(endlを使用して\ nを追加してcout.flush()を呼び出しても)バッファをフラッシュしようとすると、segfaultが発生します。サニティチェックとして、自分のコードをウェブからの例に置き換えました。私はこれも別にテストしました。私はそれを自分のファイルに入れてコンパイルすると動作します(例えば、ファイルの内容を出力し、segfaultを実行せず、flush()やendlを呼び出す必要はありません)。私のコードで。 (警告、コメントアウトがたくさん:ファイルデータの取得後にcoutをフラッシュする際の問題
ifstream is;
is.open("plain");
char c;
while (is.good()) // loop while extraction from file is possible
{
c = is.get(); // get character from file
if (is.good())
cout << c;
// cout.flush();
}
is.close(); // close file*/
ここでは完全なコードであり、ここで
は、(そのはcplusplus.comからほとんど直接コピー私のコードの罰金外を作品)コードの問題のビットがありますコード)
#include <iostream>
#include <fstream>
#include <string.h>
#include <vector>
using namespace std;
static char s[256], k[256];
//static char *i, *j;
void swap(int m, int n, char t[256]){
char tmp = t[m];
t[m] = t[n];
t[n] = tmp;
}
char getByte(){
static char i(0), j(0);
i = (i+1)%256;
j = (j + s[i])%256;
swap(i, j, s);
return s[(s[i]+s[j]) % 256];
}
int main(int argc, char ** argv){
/*string key = argv[1];*/
if(argc < 4){
cout << "Usage: \n rc4 keyfile plaintextfile outputfile" << endl;
return -1;
}
string key;
ifstream keyfile (argv[1]);
keyfile >> k;
cout << "Key = " << k << endl;
keyfile.close();
/*ifstream plaintextf;
plaintextf.open(argv[2]);*/
ofstream ciphertextf (argv[3]);
for(int q = 0; q < 256; q++){
s[q] = q;
}
int i, j;
for(int m = 0; m < 256; m++){
j = (j + s[m] + k[m % sizeof(k)])%256;
swap(m, j, s);
}
// vector<char> bytes(plaintext.begin(), plaintext.end());
// bytes.push_back('\0');
// vector<char>::iterator it = bytes.begin();
/* char pt;
while(plaintextf.good()){
pt = plaintextf.get();
if(plaintextf.good()){
cout << pt;
ciphertextf <<(char) (pt^getByte());
}
} */
ifstream is;
is.open("plain");
char c;
while (is.good()) // loop while extraction from file is possible
{
c = is.get(); // get character from file
if (is.good())
cout << c;
// cout.flush();
}
is.close(); // close file*/
/*// plaintextf.close();
ciphertextf.close();
keyfile.close();
*/
return 0;
}
おそらく、生の ''\ 0''文字をストリームに挿入しています。挿入する前に 'char'を' int'にキャストして、それが動作するかどうか確認してください。 – ildjarn
このように? cout <<(int)c; –
それは役に立たなかったので...私はちょっとここで紛失しています。 –