Skip to content

Instantly share code, notes, and snippets.

@Battleroid
Created March 18, 2013 02:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Battleroid/5184589 to your computer and use it in GitHub Desktop.
Save Battleroid/5184589 to your computer and use it in GitHub Desktop.
Set of functions to read & write information (in this case a simple sentence) to a file in binary and 'encrypt' it (just adding 5 to each character) and writing it to a new user specified file.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstring>
using namespace std;
void write(const string &input, string oname) {
fstream output(oname, ios::out | ios::binary);
if (output.is_open()) {
output.write(input.c_str(), input.size());
output.close();
}
}
string read(const string &fname) {
int size;
vector<char> buffer;
fstream input(fname, ios::in | ios::binary);
if (input.is_open()) {
input.seekg(0, ios::end);
size = input.tellg();
input.seekg(0, ios::beg);
buffer.resize(size);
input.read(&buffer.front(), size);
input.close();
}
string result(buffer.begin(), buffer.end());
return result;
}
void encrypt(string iname, string oname) {
// read
int size;
vector<char> buffer;
fstream input(iname, ios::in | ios::binary);
if (input.is_open()) {
// get size
input.seekg(0, ios::end);
size = input.tellg();
input.seekg(0, ios::beg);
// resize buffer to size
buffer.resize(size);
input.read(&buffer.front(), size);
input.close();
}
// encrypt
char* target = new char[buffer.size()];
copy(buffer.begin(), buffer.end(), target);
for (int i = 0; i < buffer.size(); i++)
target[i] += 5;
string result(target);
// output
write(result, oname);
}
int main () {
string iname, oname;
cout << "Input: ";
cin >> iname;
cout << "Output: ";
cin >> oname;
encrypt(iname, oname);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment