c++ - Simple Encryption not working -
i'm using simple encryption found online. basically, i'm streaming in file, checking see if file open (if not, display error message) , putting each line in each element of array while encrypting information. afterwards stream encrypted information onto output file.
however, i'm getting nothing in output.txt file. encryption works fine if test itself.
here code:
#include <string> #include <fstream> #include <sstream> // ostringstream #include <iostream> #include <stdio.h> #include <algorithm> /* credits kylewbanks.com */ string encrypt (string content) { char key[3] = {'k'}; //any chars work string output = content; (int = 0; < content.size(); i++) output[i] = content[i] ^ key[i % (sizeof(key) / sizeof(char))]; return output; } int main() { string input, line; string content[10000]; string encryptedcontent[10000]; int counter = 0, innerchoice = 0, i, finalcounter; cout << "\tplease enter file name encrypt!\n"; cout << "\ttype '0' menu!\n"; cout << "input >> "; cin >> input; /* reads in inputted file */ ifstream file(input.c_str()); //fopen, fscanf if(file.is_open()) { /* counts number of lines in file */ while (getline(file, line)) { counter++; } cout << counter; finalcounter = counter; (i = 0; < finalcounter; i++) { file >> content[i]; encryptedcontent[i] = encrypt(content[i]); cout << encryptedcontent[i]; } } else { cout << "\tunable open file: " << input << "!\n"; } /* write encryption file */ ofstream outputfile("output.txt"); (i = 0; < finalcounter ; i++) { outputfile << encryptedcontent; } outputfile.close(); }
any clue wrong?
string content[10000]; string encryptedcontent[10000];
this wrong because creating 20000 strings (you think creating large enough character array read data).
string content;
enough. can resized handle length of strings.
you need read/write file in binary:
int main() { string input = "input.txt"; ifstream file(input, ios::binary); if (!file.is_open()) { cout << "\tunable open file: " << input << "!\n"; return 0; } string plaintext; //read file file.seekg(0, std::ios::end); size_t size = (size_t)file.tellg(); file.seekg(0); plaintext.resize(size, 0); file.read(&plaintext[0], size); cout << "reading:\n" << plaintext << "\n"; //encrypt content string encrypted = encrypt(plaintext); //encrypt again goes original (for testing) string decrypted = encrypt(encrypted); cout << "testing:\n" << decrypted << "\n"; /* write encryption file */ ofstream outputfile("output.txt", ios::binary); outputfile.write(encrypted.data(), encrypted.size()); return 0; }
Comments
Post a Comment