Suppose an encrypted file was created using the encoding/decoding scheme. Each l
ID: 3762444 • Letter: S
Question
Suppose an encrypted file was created using the encoding/decoding scheme. Each letter is substituted by some other letter according to a given mapping as shown below.
char * letters = "abcdefghijklmnopqrstuvwxyz";
char * enc = "kngcadsxbvfhjtiumylzqropwe";
For example, every 'a' becomes a 'k' when encoding a text, and every 'k' becomes an 'a' when decoding.
You will need to write a program in C that encodes or decodes a File, and then encodes or decodes the File using the mapping above. Capital letters are mapped the same way as the lower case letters above, but remain capitalized. For example, every 'A' becomes 'K' when encoding a file, and every 'K' becomes an 'A' when decoding. Numbers and other characters are not encoded and remain the same.
Write a program in C to read a file and encode the file to an encrypted file. And write a program to get an encrypted file and decode to original file. Your program should prompt the user to enter an input file name and an output file name
Guidelines: What should you do?
- Ask for input file name/ output file name (encrypted file). The encrypt using above encode/decode.
- Ask for encrypted file and decoded to original input file.
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
FILE *fp, *out;
char inFileName[255];
char outFileName[255];
int in, i;
char ch;
char * letters = "abcdefghijklmnopqrstuvwxyz";
char * enc = "kngcadsxbvfhjtiumylzqropwe";
printf("Enter 1 to encrypt a file or 2 to decrypt a file: ");
scanf("%d", &in);
printf("Enter input file name: ");
scanf("%s", inFileName);
fp = fopen(inFileName, "r");
out = fopen(outFileName, "w");
if (in ==1 || in ==2) {
while ((ch = fgetc(fp)) != EOF) {
if (in == 1) {
if (ch >= 'a' && ch <='z') {
fprintf(out, "%c", enc[ch-'a']);
} else if (ch >= 'A' && ch <='Z') {
fprintf(out, "%c", 'A' + enc[ch-'A']-'a');
} else {
fprintf(out, "%c", ch);
}
} else {
if (ch >= 'a' && ch <='z') {
for (i=0; i<26; i++) {
if (enc[i] == ch) {
fprintf(out, "%c", letters[i]);
break;
}
}
} else if (ch >= 'A' && ch <='Z') {
fprintf(out, "%c", 'A' + enc[ch-'A']);
for (i=0; i<26; i++) {
if (enc[i] == (ch-'A')) {
fprintf(out, "%c", letters[i]-'a'+'A');
break;
}
}
} else {
fprintf(out, "%c", ch);
}
}
}
} else {
printf("Wrong input!!");
}
printf(" ");
return 0;
}