In: Computer Science
In this assignment you will write a program that encrypts a text file. You will use the following encryption scheme.
This same program can be used to decrypt a file that has been encrypted in this way.
Your program should have functions for performing each of the following tasks.
Your main function should get the filenames, open the files, get the key, dynamically allocate the memory for the array, and close the files.
Your program should also:
Give detailed directions and warnings to the user.
Code is as following:
#include <iostream>
#include <fstream>
#include <bits/stdc++.h>
using namespace std;
//transpose the array
void transpose(char *A, char *B, int n){
int i, j;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
*((B+i*n)+j) = *((A+j*n)+i);
}
//read the characters to the array
void readCharsToArray(ifstream &fin,char *arr,int n){
char ch;
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
if(fin >> noskipws >> ch)
*(arr+(i*n)+j) = ch;
else
break;
}
}
}
int main() {
int n = 0; string inFile, outFile;
cout<<"Enter input file name: ";
cin>>inFile;
cout<<"Enter output file name: ";
cin>>outFile;
while(n<1){
cout<<"Enter key('n'):"<<endl;
cin>>n;
if(n<1)
cout<<"Enter valid key!!"<<endl;
}
//construct n-by-n matrix
char arr[n][n];
char temp[n][n];
memset(arr,'$',sizeof(arr));
//open input file
ifstream fin(inFile);
ofstream fout;
//first open output file to format all content, if it already exists
fout.open(outFile);
fout.close();
//open output file in append mode
fout.open(outFile,ios::app);
while(fin){
readCharsToArray(fin,arr[0],n);
transpose(arr[0],temp[0],n);
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
if(temp[i][j]!='$')
fout<<temp[i][j];
}
}
memset(arr,'$',sizeof(arr));
}
fin.close();
fout.close();
}
Sample output after running program on file "input.txt"
Following Sample output is shown on the following input.txt file:-
Output of file encrypt.txt is as following:-
Output of second run on file "encrypt.txt" is as following:
Output of decrypt.txt file is as following:-
Note - If any doubt/queries, do ask in comment section