Please work on C++ You can ONLY use given #include code you are working on Resta
ID: 3889619 • Letter: P
Question
Please work on C++
You can ONLY use given #include
code you are working on
Restart your subscription to keep accessing solutions. Your Chegg Study subscription will expire on September 28, 2017. CONTINUE MY SUBSCRIPTION
home / study / engineering / computer science / computer science questions and answers / please work on c++ you can only use given #include code you are working on #include #include ...
Your question has been posted.
We'll notify you when a Chegg Expert has answered. Post another question.
Question: Please work on C++ You can ONLY use given #include code you are working on #include <fstream&g...
Please work on C++
You can ONLY use given #include
code you are working on
#include <fstream>
#include <string>
#include <algorithm>
void encrypt_file(const std::string& filename, const std::string& password) {
}
Test code(cannot change):
#include <iostream>
int main() {
std::string testFilename;
// Tests your encrypt_file function on test01 through test09
for (int i = 1; i <= 9; ++i) {
testFilename = std::string("test0") + (char) (i + 48);
encrypt_file(testFilename + "-unzipped", "password");
if (cmp_files(testFilename + "-unzipped-encrypted", testFilename + "-unzipped-encrypted-expected")) {
std::cout << "Encryption was correctly performed for " << testFilename << "!" << std::endl;
} else {
std::cout << "Something went wrong encrypting " << testFilename << " :(" << std::endl;
return -1;
}
}
Explanation / Answer
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std; // specifying the namespace to be used
void encrypt_file(const std::string& filename, const std::string& password) {
ifstream ifs(filename.c_str(), ios::binary|ios::ate); /* opening the binary file and keeping the current position to the end */
ifstream::pos_type pos = ifs.tellg(); /* taking the end position in the variable pos. This will help in knowing the size of the file */
int length = pos; // length is the variable to hold the size of the file
std::vector<char> result(pos); // a vector to hold the byte wise file data
ifs.seekg(0, ios::beg);
ifs.read(&result[0], pos); // reading data from the file into the byte vector
char encryptedData[length+1]; // byte array to hold the final result after XORing the data
int passwordLength = password.size(); // a variable to hold length of the password
for(int i = 0;i<length; i++)
{
encryptedData[i] = result[i]^password[i%passwordLength]; /* handling the cyclic nature of password as mentioned in the question */
}
encryptedData[length] = '';
ifs.close();
// Now, we will write the data to the output file
ofstream fout;
string outputfilename = filename + "-encrypted";
fout.open(outputfilename.c_str(), ios::binary | ios::out);
fout.write((char*) &encryptedData, sizeof(encryptedData));
fout.close();
}